【问题标题】:Can I use a List<T> as a collection of method pointers? (C#)我可以使用 List<T> 作为方法指针的集合吗? (C#)
【发布时间】:2023-03-05 20:51:01
【问题描述】:

我想创建一个要执行的方法列表。每个方法都有相同的签名。 我曾考虑将代表放在通用集合中,但我不断收到此错误:

“方法”是一个“变量”,但用作“方法”

理论上,这是我想做的:

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);
}

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

【问题讨论】:

    标签: c# generics delegates


    【解决方案1】:

    您需要将列表中的object 强制转换为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);
    }
    

    【讨论】:

      【解决方案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)
      

      【讨论】:

      • 最后一行不应该是:methodsToExecute[0](1,2);甚至 beeter: int n = methodsToExecute[0](1,2);
      【解决方案3】:
      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));
      

      【讨论】:

        【解决方案4】:

        我更喜欢 Khoth 的实现,但我认为导致编译器错误的原因是在尝试调用方法之前没有将方法转换为 BinaryOp。在您的 foreach 循环中,它只是一个“对象”。将你的 foreach 改成 Khoth 的样子,我认为它会起作用。

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

            没试过,但是使用List>类型应该可以做到。

            【讨论】:

              【解决方案7】:

              让它们都实现通用接口,比如 IExecuteable,然后有一个 List

              另外,使用委托:

              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;
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-12-10
                • 1970-01-01
                • 2021-06-11
                • 2021-12-14
                • 1970-01-01
                • 2011-04-17
                • 2011-06-12
                • 1970-01-01
                相关资源
                最近更新 更多