简体   繁体   English

c#反射调用未知类型的委托方法

[英]c# reflection to invoke delegate method with unknown type

// cant modiy this code, it's 3rd libray
public class TestClass{
    public void TestMethod(Class2 class2){
    }
    
    public void TestMethod(Class3 class3){
    }
}
public class Class2{}
public class Class3{}
var Class2Type = System.Reflection.Assembly.GetExecutingAssembly().GetType("Class2");
var TestMethodType = typeof(TestClass).GetMethod("TestMethod",new Type[] { Class2Type });
var del = TestMethodType.CreateDelegate(typeof(Action<,>).MakeGenericType(typeof(TestClass),Class2Type));
// how to invoke TestMethod using del?

if Class2 is a known type, we can invoke TestMethod using del like this:如果 Class2 是已知类型,我们可以使用 del 调用 TestMethod ,如下所示:

var del = (Action<TestClass, Class2>)TestMethodType.CreateDelegate(typeof(Action<TestClass, Class2>));
del(new TestClass(), new Class2());

but if "Class2" is unkonwn dynamic string, I dont know how to do it?但是如果“Class2”是未知的动态字符串,我不知道该怎么做?

So, if I understand correctly, you are trying to invoke the right overload method, based on the type (which is not known compiletime)因此,如果我理解正确,您将尝试根据类型(未知的编译时间)调用正确的重载方法

In this case you cannot use generics, because the type isn't known.在这种情况下,您不能使用泛型,因为类型未知。 You will probably manage to create a generic type, based on the class2, but the next problem is calling it.您可能会根据 class2 创建一个泛型类型,但下一个问题是调用它。 So strongtyped in not the way.所以强类型不是这样。 IMHO恕我直言

You can just call Invoke on the MethodInfo.您可以只对 MethodInfo 调用 Invoke。

Here is an example:下面是一个例子:

// search for the class2Type (I changed it a little so I can test it)
var class2Type = System.Reflection.Assembly.GetExecutingAssembly().GetType("TestProgram.Class2");

// Searching for the right (overloaded) method.
var testMethodType = typeof(TestProgram.TestClass).GetMethod("TestMethod", new Type[] { class2Type });

// create an instance of the TestClass (which is a known type)
var testClassInstance = new TestProgram.TestClass();

// create the instance of the class2 (which isn't a known type)
var class2Instance = Activator.CreateInstance(class2Type);

// invoke the testMethod and pass the class2 instance in it.
// you need to pass the testClassInstance also.
testMethodType.Invoke(testClassInstance, new[] { class2Instance });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM