lundi 13 juin 2022

Using reflection, how can I find the Method that takes arguments defined in the reflected library itself?

I have a library written in .NET461 and I would like to call a method in that library using reflection

The class itself looks something like ...

public class ClassA {
}
...
public class ClassB {
  public MethodA( ClassA val )
  {
    ..
  }  

  public MethodA( List<ClassA> list )
  {
    ..
  }  
}

My calling exe is a .NET48 executable...

(removed validation and some code for brevity)

// get the library
var asm = Assembly.LoadFrom( "...myAssembly.dll" );

// instantiate ClassB
var instance = asm.CreateInstance( "ClassB" )

// look for that class type so we can get the method "MethodA"
var type = asm.GetExportedTypes().FirstOrDefault( t => t.Name == "ClassB" ); 

// look for all the methods called "MethodA"
// this call works and I can see I have 2 methods with that name
var methods = type.GetMethods().Where(m => m.Name == "MethodA").ToList();

// look for the method just by that name.
// Here I get an error as there are 2 methods with the same name.
var method = type.GetMethod( "MethodA");

It is possible to get the method if I pass the parameters but the 'type' in the list is supposed to be a list of List<ClassA>

How can I find the method with a parameter of "List<ClassA>" when ClassA itself is defined in the library and not in my executable.

...
var methodA = type.GetMethod("MethodA", new []
          {
            typeof(List<ClassA>>)                  // <<<< ClassA is not defined here. 
                                                   //      It is defined in the library
          } );




Aucun commentaire:

Enregistrer un commentaire