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

时间:2020-03-06 14:44:37  来源:igfitidea点击:

我想创建要执行的方法的列表。每种方法具有相同的签名。
我曾考虑过将委托放入通用集合中,但始终出现此错误:

'method' is a 'variable' but is used like a '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);
}

关于如何做到这一点的任何想法?
谢谢!

解决方案

让它们全部实现通用接口,例如IExecuteable,然后具有List <IExecutable>

另外,使用委托:

class Example
{
    public delegate int AddDelegate(int x, int y);

    public List<AddDelegate> methods = new List<AddDelegate>();

    int Execute()
    {
        int sum = 0;
        foreach(AddDelegate method in methods)
        {
            sum+=method.Invoke(1, 2);
        }
        return sum;
    }
}

还没有尝试过,但是使用List <Action <t >>类型应该可以做到。

我们需要将列表中的"对象"强制转换为" 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);
}

使用.NET 3.0(或者3.5?),我们可以使用泛型委托。

试试这个:

List<Func<int, int, int>> methodsToExecute = new List<Func<int, int, int>>();

methodsToExecute.Add(Subtract);

methodsToExecute.Add[0](1,2); // equivalent to Subtract(1,2)

List<Func<int, int, int>> n = new List<Func<int, int, int>>();
            n.Add((x, y) => x + y);
            n.Add((x, y) => x - y);
            n.ForEach(f => f.Invoke(1, 2));

我更喜欢Khoth的实现,但是我认为导致编译器错误的原因是我们在尝试调用BinaryOp之前没有将方法转换为BinaryOp。在foreach循环中,它仅仅是一个"对象"。更改foreach使其看起来像Khoth的样子,我认为它会起作用。

每当我想做这样的事情时,我发现通常最好重构设计以使用命令模式,特别是因为所有方法都具有相同的参数。这样可以提供更大的灵活性。