Skip to main content
 首页 » 编程设计

c#之创建具有动态操作参数的方法

2024年02月06日11sky-heaven

嗨,有没有办法创建一个接受任何类型方法的方法?我的意思是它有任何类型的参数或它有多少参数

void SampleMethod(Action<dynamic> Action) 
{ 
} 

我目前正在这样做,但我认为我做错了,有没有办法做到这一点?无论是有参数还是多参数还是无参数。

我是做错了什么还是错过了什么?

我试过这段代码

void SampleMethod(Action Action) 
{ 
} 

但是好像只接受没有参数的方法 我做错了吗?

请您参考如下方法:

我认为Delegate正是您要找的。

static void A1() { 
  Console.Out.WriteLine("A1"); 
} 
 
static void A2(int foo) { 
  Console.Out.WriteLine("A2"); 
} 
 
static void SampleMethod(Delegate dlgt) { 
} 

用法:

SampleMethod(new Action(A1)); 
SampleMethod(new Action<int>(A2)); 

您可以通过DynamicInvoke调用该方法(),但是您必须提供确切的参数列表。

static void SampleMethod(Delegate dlgt) { 
  // ok for A1, will throw an exception for A2 
  dlgt.DynamicInvoke(null); 
}