Reputation: 1082
Hi is there a way to create a method which accepts any kind of method? i mean any kind of parameter it has or how many parameter it has
void SampleMethod(Action<dynamic> Action)
{
}
I'm currently doing it like it but i think i doing it wrong is there a way to do that? whether it has a parameter or many or without parameter.
Am i doing wrong or i just miss something?
I have tried this code
void SampleMethod(Action Action)
{
}
but it seems that it only accepts the method without a parameter Am i doing wrong?
Upvotes: 1
Views: 3227
Reputation: 5716
With Reflection,
SampleMethod(this.GetType().GetMethod("WriteHello"), "Hello");
public void WriteHello(string param)
{
Debug.WriteLine(param);
}
public void SampleMethod(MethodInfo mi, params object[] arguments)
{
mi.Invoke(this,arguments);
}
Upvotes: 2
Reputation: 22054
I think Delegate
is what you're looking for.
static void A1() {
Console.Out.WriteLine("A1");
}
static void A2(int foo) {
Console.Out.WriteLine("A2");
}
static void SampleMethod(Delegate dlgt) {
}
Usage:
SampleMethod(new Action(A1));
SampleMethod(new Action<int>(A2));
You can invoke the method via DynamicInvoke
(), however you'll have to provide exact list of arguments.
static void SampleMethod(Delegate dlgt) {
// ok for A1, will throw an exception for A2
dlgt.DynamicInvoke(null);
}
Upvotes: 3