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

标签 c# c#-4.0 reflection types

Type.GetType("TheClass");

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

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

有什么办法可以避免给 namespace 起名字吗?

最佳答案

我使用了一种辅助方法来搜索所有已加载的 Assembly s 表示 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();
}

关于c# - 避免在 Type.GetType() 中给出命名空间名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9273629/

相关文章:

c# - 反射(reflection)动态类型以判断它是否是动态类型,首先

c# - 如何在 C# 中打开与 Microsoft Access 数据库的连接

c# - 使用反射调用方法时处理空参数

C# EF 必需属性无法识别

java - 使用反射调用随机方法

c# - 选中复选框时防止出现多个主项

c# - 如何从 xamarin.forms 调用平台特定页面

C#4.0 : How to find out if types are co-variantly equal

c# - 调用 Dispatch/LUIS 模型时操作返回无效状态代码 ‘Unauthorized’

c# - 使用 ASP.NET 样板将 ValueObject 存储在数据库中