Type.GetType("NameSpace.ClassName", false, true) returns null. What could be wrong?
I am trying to create instance of class by using reflection in ASP.net web site. Class ClassName is defined and located in App_code folder. Following line returns null, what coul开发者_如何学Pythond be wrong.
Type type = Type.GetType("NameSpace.ClassName", false, true);
Supplying only the type name works only in the following scenarios:
- The type in question is in the currently executing assembly (i.e., the same assembly as your code)
OR
- The type in question is in
mscorlib.dll
.
In all other cases, you have to supply the assembly-qualified name of the type. This is what allows it to locate the appropriate assembly and load it.
You can use System.Web.Compilation.BuildManager.GetType e.g.
using System.Web.Compilation;
Type t = BuildManager.GetType("NameSpace.ClassName", true);
Afin, try this. This is to piggyback on Adam Robinson's answer and to demonstrate what you need to do to test the statements made in the answer and the comments for yourself.
Type t = typeof(YourNamespace.YourClass);
string assemblyQualifiedName = t.AssemblyQualifiedName;
Type type = Type.GetType(assemblyQualifiedName, false, true);
// type will not be null
The assembly qualified name will be something like "Sample.Foo, App_Code.qwijwhsy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null".
Try using Assembly.GetType(), that should look in the referenced assembly. Of course, you'd need to load the appropriate Assembly class, which would be GetCallingAssembly() if the type shares assembly with your executing code, or something else otherwise, in which case you'd use one of the static LoadSomething() methods within the Assembly class.
For instance:
Type type = LoadFrom("App_code\ClassAssembly.dll").GetType("Namespace.ClassName");
// Load assembly, then type!
Type type2 = GetCallingAssembly().GetType("Namespace.ClassName");
// If it's the same assembly as the calling code.
Very simple code. I think that it doesn't need any explaining.
using System.Reflection;
Assembly assembly = Assembly.LoadFrom("MyLibrary.dll");
Type type = assembly.GetType("NameSpace.ClassName", false, true);
if its in App_Code try
Type t = Type.Get("Namespace.ClassName, __code");
精彩评论