开发者

GetType in .NET Reflection does not work

I'm trying to call

Type.GetType("System.Diagnostics.TraceFilter")

not typeof(System.Diagnostics.TraceFilter)

but the result is always null. Could anyone help me 开发者_高级运维out? How to get class type for this abstract class?


From the documentation for Type.GetType(string typeName)

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

The type you are fishing around for (i.e. "System.Diagnostics.TraceFilter") is not in the currently executing assembly or in "Mscorlib.dll", it is in fact in "System.dll". Therefore you have to use the fully qualified assembly name, e.g.:

 Type type = Type.GetType("System.Diagnostics.TraceFilter, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Alternatively you can use:

 Type type = typeof(System.Diagnostics.TraceFilter);


It's probably because you must provide an assembly-qualified name.

Better, though, would be to use this instead:

typeof(System.Diagnostics.TraceFilter)


According to MSDN, Type.GetType(string) requires an assembly-qualified name unless the target type is either in the currently executing assembly or mscorlib.dll. System.Diagnostics.TraceFilter is in System.dll, which means that you must use an assembly-qualified name.


Sometimes even if the right assembly is loaded you can't use reflection as you might expect. It often happens when using injection frameworks like MEF or Unity. If typeof() operator is not an option and Type.GetType() fails then this function usually does the trick:

public static Type GetTypeEx(string fullTypeName)
{
 Type type = Type.GetType(fullTypeName);
 if (type != null)
     return type;

 foreach (System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
 {
     Type t2 = assembly.GetType(fullTypeName);
     if (t2 != null)
         return t2;
 }
 return null;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜