使用类名称的字符串来新建一个类

时间:2019-04-16 09:02:45

标签: c# reflection

我想使用一个类名字符串来新建一个类

NameSpace为Mcs.ControlMaster

类名是HostTransportCommand

在此处查看一些帖子后。我使用激活器

var msg = Activator.CreateInstance(Type.GetType("Mcs.ControlMaster.HostTransportCommand", true));

获得例外

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'Mcs.ControlMaster.HostTransportCommand' from assembly 'Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

好的,执行程序集现在是Mcs.ControlMaster.UT。此类在Mcs.ControlMaster中。然后

string fileToLoad = @"Mcs.ControlMaster.exe";
AssemblyName assamblyName = AssemblyName.GetAssemblyName(fileToLoad);
// assamblyName={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
//myDomain={System.Runtime.Remoting.Proxies.__TransparentProxy}
Assembly myAssambly = myDomain.Load(assamblyName);
//myAssambly={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
var myFunc = myAssambly.CreateInstance("HostTransportCommand");
// myFunc = null

如果使用

Type.GetType("Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", true));

将获得

System.IO.FileLoadException: "The given assembly name or codebase was invalid." 

HostTransportCommand的定义

namespace Mcs.ControlMaster
{
    public class HostTransportCommand : JsonMessage

和JsonMessage的定义

namespace Mcs.Message
{
  public class JsonMessage : IMcsMessage

namespace Mcs.Message
{
  public interface IMcsMessage

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Source code demo in my Github (batressc)

我使用您的类定义创建了2个项目(.net框架类库):Mcs.ControllerMasterMcs.Message。我在第三个项目Mcs.ControllerMaster(Windows控制台应用程序)中引用了Msc.WindowsConsole

出于测试目的,我向HostTransportCommand添加了2个属性:

public class HostTransportCommand : JsonMessage {
    public string PropertyOne { get; set; }
    public int PropertyTwo { get; set; }
}

然后,在Main方法中,我按照以下步骤操作:

class Program {
    static void Main(string[] args) {
        // Getting current execution directory
        var currentExecutingPath = Assembly.GetExecutingAssembly().CodeBase;
        string dirtyDirectory = Path.GetDirectoryName(currentExecutingPath);
        string directory = dirtyDirectory.Replace(@"file:\", "");

        // Loading assembly in app context
        var externalAssembly = File.ReadAllBytes($"{directory}\\Mcs.ControlMaster.dll");
        AppDomain.CurrentDomain.Load(externalAssembly);

        // Now is loading. Creating an instance of class
        // The object type is "ObjectHandle"
        var hostTransportCommandInstance = Activator.CreateInstance("Mcs.ControlMaster", "Mcs.ControlMaster.HostTransportCommand");

        // Getting properties for validate instance creation
        // Using Unwrap() method we can access to true Type (HostTransportCommand)
        var hostTransportCommandType = hostTransportCommandInstance.Unwrap().GetType();
        var hostTransportCommandProperties = hostTransportCommandInstance.Unwrap().GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        // Showing information about type HostTransportCommand
        Console.WriteLine($"The type from Mcs.ControllerMaster is {hostTransportCommandType}");
        Console.WriteLine("Showing public properties (they was added for testing purposed):");
        foreach (PropertyInfo property in hostTransportCommandProperties) {
            Console.WriteLine(property.Name);
        }
        Console.ReadKey();
    }
}