我有一个用 .NET461 编写的库,我想使用反射调用该库中的一个方法
类本身看起来像......
public class ClassA {
}
...
public class ClassB {
public MethodA( ClassA val )
{
..
}
public MethodA( List<ClassA> list )
{
..
}
}
我的调用 exe 是一个 .NET48 可执行文件...
(为简洁起见,删除了验证和一些代码)
// 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");
如果我传递参数,则可以获得该方法,但列表中的“类型”应该是List<ClassA>
我怎样才能找到带有参数的方法,List<ClassA>
当ClassA
它本身是在库中定义的而不是在我的可执行文件中时。
...
var methodA = type.GetMethod("MethodA", new []
{
typeof(List<ClassA>>) // <<<< ClassA is not defined here.
// It is defined in the library
} );
您可以获取与获取类型变量ClassA
相同的方式,ClassB
然后构造参数类型并获取所需的方法:
var asm = Assembly.LoadFrom( "...myAssembly.dll" );
var assemblyTypes = asm.GetExportedTypes();
var classAType = assemblyTypes.FirstOrDefault( t => t.Name == "ClassA" );
var classBType = assemblyTypes.FirstOrDefault( t => t.Name == "ClassB" );
var instance = asm.CreateInstance( "ClassB" ); // or Activator.CreateInstance(classBType);
// construct parameter type - List<ClassA> type
var listOpenGenericType = typeof(List<>);
// List<ClassA>
var listClosedGenericType = listOpenGenericType.MakeGenericType(classAType);
// find the method
var method = classBType
.GetMethods()
.Where(m => m.Name == "MethodA")
.FirstOrDefault(m =>
{
var parameters = m.GetParameters();
return parameters.Length == 1 && parameters.First().ParameterType == listClosedGenericType);
});
if (method != null)
{
// call method
method.Invoke(instance, yourList); // pass list
}
// ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句