通过卫星装配的反​​射创建一个对象

时间:2011-05-31 09:59:33

标签: c# asp.net reflection

我有两个以DLL作为输出的程序集/项目:模型和逻辑

在Logic DLL中我想通过反射创建一个特定模型的对象(该项目被引用,我能够手动创建一个实例)

MyNameSpace.Models.Foo foo = new MyNameSpace.Models.Foo(); // works
Type type = Type.GetType("MyNameSpace.Models.Foo"); // returns null

如何创建MyNameSpace.Models.Foo的对象?显然这种类型无法解决。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您必须使用AssemblyQualifiedName。有关详细信息,请参阅此文章:http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx

在您的情况下,例如:

MyNamespace.Models.Foo, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089

如果您已签署程序集,则PublicKeyToken可能会更长。

如果您不确定,只需按常规方式创建对象的实例,然后执行:

Type objType = typeof(System.Array);

// Print the full assembly name.
Console.WriteLine ("Full assembly name: {0}.", objType.Assembly.FullName.ToString()); 

// Print the qualified assembly name.
Console.WriteLine ("Qualified assembly name: {0}.", objType.AssemblyQualifiedName.ToString());

(从前面提到的文章中无可挑剔)

答案 1 :(得分:1)

您可以查看使用Activator.CreateInstance。例如:

Assembly assembly = Assembly.LoadFrom("Foo.dll");

Type type = assembly.GetType("TheNamspace.TheType");

object instanceOfMyType = Activator.CreateInstance(type);

答案 2 :(得分:0)

Type.GetType参数是AssemblyQualifiedName:来自MSDN