本文介绍了避免在Type.GetType()中给出命名空间名称,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Type.GetType(TheClass);
返回 null
如果命名空间
不存在,如:
Type.GetType(SomeNamespace.TheClass); //返回一个Type对象
有没有办法避免给出命名空间
我使用了一个帮助方法搜索所有加载的用于匹配指定的名称。即使在我的代码只有一个类型结果预期它支持多。我验证每次使用它时只返回一个结果,并建议您也这样做。
///< summary> ;
///获取与指定类名称匹配的所有类型实例,只使用非命名空间限定类名。
///< / summary>
///< param name =className>寻找的类名。< / param>
///< return>指定类名的类型。它们可能不在同一命名空间中。< / returns>
public static Type [] getTypeByName(string className)
{
List< Type> returnVal = new List< Type>();
foreach(在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("TheClass");
Returns null
if the namespace
is not present like:
Type.GetType("SomeNamespace.TheClass"); // returns a Type object
Is there any way to avoid giving the namespace
name?
解决方案 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()中给出命名空间名称,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!