本文介绍了避免在 Type.GetType() 中给出命名空间名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Type.GetType("TheClass");
如果 namespace
不存在,则返回 null
,例如:
Returns null
if the namespace
is not present like:
Type.GetType("SomeNamespace.TheClass"); // returns a Type object
有什么办法可以避免给namespace
命名?
Is there any way to avoid giving the namespace
name?
推荐答案
我使用了一个辅助方法来搜索所有加载的 Assembly 用于类型匹配指定的名称.即使在我的代码中只预期一个 Type 结果,它也支持多个.我确认每次使用它时只返回一个结果,并建议您也这样做.
I've used a helper method that searches all loaded Assemblys for a Type matching the specified name. Even though in my code only one Type result was expected it supports multiple. I verify that only one result is returned every time I used it and suggest you do the same.
/// <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();
}
这篇关于避免在 Type.GetType() 中给出命名空间名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!