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/