避免在Type.GetType()中给出命名空间名称

时间:2012-02-14 08:16:34

标签: c# c#-4.0 reflection types

Type.GetType("TheClass");

如果null不存在,则返回namespace,如:

Type.GetType("SomeNamespace.TheClass"); // returns a Type object 

有没有办法避免提供namespace名称?

4 个答案:

答案 0 :(得分:44)

我使用了一个帮助方法,在所有已加载的Assembly中搜索与指定名称匹配的Type。尽管在我的代码中只预期一个Type结果,但它支持多个。我验证每次使用它时只返回一个结果,并建议你也这样做。

/// <summary>
/// Gets a all Type instances matching the specified class name with just non-namespace qualified class name.
/// </summary>
/// <param name="className">Name of the class sought.</param>
/// <returns>Types that have the class name specified. They may not be in the same namespace.</returns>
public static Type[] getTypeByName(string className)
{
    List<Type> returnVal = new List<Type>();

    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
    {
        Type[] assemblyTypes = a.GetTypes();
        for (int j = 0; j < assemblyTypes.Length; j++)
        {
            if (assemblyTypes[j].Name == className)
            {
                returnVal.Add(assemblyTypes[j]);
            }
        }
    }

    return returnVal.ToArray();
}

答案 1 :(得分:1)

这应该有效

AppDomain.CurrentDomain
    .GetAssemblies()
    .SelectMany(x => x.GetTypes())
    .FirstOrDefault(t => t.Name == "MyTypeName");

Where代替FirstOrDefault用于数组或结果

答案 2 :(得分:0)

简单缓存版本

做一次....

        nameTypeLookup = typeof(AnyTypeWithin_SomeNamespace).Assembly
            .DefinedTypes.Where(t => t.DeclaringType == null)
            .ToDictionary(k => k.Name, v => v);

用法 - 通过字典多次查找

nameTypeLookup["TheClass"];

答案 3 :(得分:-1)

这是方法期望获得的参数,所以没有。你不能。

  

typeName:由其名称空间限定的类型名称。

MSDN

您希望如何区分具有相同名称但名称空间不同的两个类?

namespace one
{
    public class TheClass
    {
    }
}

namespace two
{
    public class TheClass
    {
    }
}

Type.GetType("TheClass") // Which?!
相关问题