Let’s say I have a delegate…
public delegate void MyAction(params object[] args);
And a class with a subclass that uses that delagate…
public class MyClass {
public List<MySubClass> mySubClasses;
}
public class MySubClass {
public string myString;
public MyAction myDelegateMethod;
}
I want to be able to pass any method to myDelegateMethod, which could accept any number of arguments with varying types, at runtime. Something like this…
MyClass myClass = new MyClass(){
mySubClasses = {
new MySubClass {
myString = "help",
myDelegateMethod = Method1
},
new MySubClass {
myString = "me",
myDelegateMethod = Method2
}
}
};
public string Method1(object myObject) { ... }
public string Method2(string value, Guid id) { ... }
How would I call each of these methods at runtime passing the appropriate arguments in?
myClass.mySubClasses.ForEach(x => {
x.myDelegateMethod; // <-- this is where I'm stumped. how do i pass arguments here?
});
Is this possible? Perhaps I have something implemented wrong?
This isn’t possible, because
Method1andMethod2are NOTvoid <Name> (params object)delegates. They aren’t the same type (or even convertible with variance to a compatible type), considering they return different values and take different parameters to execute.If you wanted to execute an arbitrary method, then the only way I can think of would be to take a wrapped method execution as an action:
And then you could execute like so:
In this situation you need to explicitly wrap whatever you want to do (with parameters known at create time) the method you want to stick in
Method.