简体   繁体   中英

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:

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?

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. So strongtyped in not the way. IMHO

You can just call Invoke on the MethodInfo.

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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