通过卫星组件的反射创建对象

问题描述

| 我有两个以DLL作为输出的程序集/项目:模型和逻辑 在Logic DLL中,我想通过反射创建特定模型的对象(已引用该项目,并且能够手动创建实例)
MyNameSpace.Models.Foo foo = new MyNameSpace.Models.Foo(); // works
Type type = Type.GetType(\"MyNameSpace.Models.Foo\"); // returns null
如何创建
MyNameSpace.Models.Foo
的对象?显然类型无法解析。我怎样才能解决这个问题?     

解决方法

        您可以看看使用ѭ2look。例如:
Assembly assembly = Assembly.LoadFrom(\"Foo.dll\");

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

object instanceOfMyType = Activator.CreateInstance(type);
    ,        您将必须使用AssemblyQualifiedName。请参阅本文:http://msdn.microsoft.com/zh-cn/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());
(无耻地从上述文章中切掉)     ,        Type.GetType参数是AssemblyQualifiedName:来自MSDN