避免在Type.GetType()中给出命名空间名称
Type.GetType("TheClass");
如果namespace
不存在,则返回null
,如:
Type.GetType("SomeNamespace.TheClass"); // returns a Type object
有没有办法避免给出namespace
名称?
我使用了一个帮助器方法,在所有已加载的Assembly中搜索与指定名称匹配的Type 。 尽管在我的代码中只预期一个Type结果,但它支持多个。 我validation每次使用它时只返回一个结果,并建议你也这样做。
/// /// Gets a all Type instances matching the specified class name with just non-namespace qualified class name. /// /// Name of the class sought. /// Types that have the class name specified. They may not be in the same namespace. public static Type[] getTypeByName(string className) { List returnVal = new List (); 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(); }
这是方法期望获得的参数,所以没有。 你不能。
typeName:由其名称空间限定的类型名称。
MSDN
您如何期望区分具有相同名称但名称空间不同的两个类?
namespace one { public class TheClass { } } namespace two { public class TheClass { } } Type.GetType("TheClass") // Which?!