我可以使用List <T>作为方法指针的集合吗?(C#)

Bre*_*ker 6 c# generics delegates

我想创建一个要执行的方法列表.每种方法都具有相同的签名.我想过将委托放在一个通用集合中,但我一直收到这个错误:

'method'是'变量',但用作'方法'

从理论上讲,这就是我想做的事情:

List<object> methodsToExecute;

int Add(int x, int y)
{ return x+y; }

int Subtract(int x, int y)
{ return x-y; }

delegate int BinaryOp(int x, int y);

methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));

foreach(object method in methodsToExecute)
{
    method(1,2);
}
Run Code Online (Sandbox Code Playgroud)

有关如何实现这一目标的任何想法?谢谢!

Kho*_*oth 15

您需要object将列表中的内容转换为a BinaryOp,或者更好地使用列表的更具体的类型参数:

delegate int BinaryOp(int x, int y);

List<BinaryOp> methodsToExecute = new List<BinaryOp>();

methodsToExecute.add(Add);
methodsToExecute.add(Subtract);

foreach(BinaryOp method in methodsToExecute)
{
    method(1,2);
}
Run Code Online (Sandbox Code Playgroud)