[英]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?
如果 Class2 是已知類型,我們可以使用 del 調用 TestMethod ,如下所示:
var del = (Action<TestClass, Class2>)TestMethodType.CreateDelegate(typeof(Action<TestClass, Class2>));
del(new TestClass(), new Class2());
但是如果“Class2”是未知的動態字符串,我不知道該怎么做?
因此,如果我理解正確,您將嘗試根據類型(未知的編譯時間)調用正確的重載方法
在這種情況下,您不能使用泛型,因為類型未知。 您可能會根據 class2 創建一個泛型類型,但下一個問題是調用它。 所以強類型不是這樣。 恕我直言
您可以只對 MethodInfo 調用 Invoke。
下面是一個例子:
// 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.