Correct Way to Load Assembly, Find Class and Call Run() Method

前端 未结 5 954
刺人心
刺人心 2020-11-22 12:17

Sample console program.

class Program
{
    static void Main(string[] args)
    {
        // ... code to build dll ... not written yet ...
        Assembly a         


        
5条回答
  •  無奈伤痛
    2020-11-22 12:42

    If you do not have access to the TestRunner type information in the calling assembly (it sounds like you may not), you can call the method like this:

    Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
    Type     type     = assembly.GetType("TestRunner");
    var      obj      = Activator.CreateInstance(type);
    
    // Alternately you could get the MethodInfo for the TestRunner.Run method
    type.InvokeMember("Run", 
                      BindingFlags.Default | BindingFlags.InvokeMethod, 
                      null,
                      obj,
                      null);
    

    If you have access to the IRunnable interface type, you can cast your instance to that (rather than the TestRunner type, which is implemented in the dynamically created or loaded assembly, right?):

      Assembly assembly  = Assembly.LoadFile(@"C:\dyn.dll");
      Type     type      = assembly.GetType("TestRunner");
      IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
      if (runnable == null) throw new Exception("broke");
      runnable.Run();
    

提交回复
热议问题