【问题标题】:How to store delegates in a List如何将代表存储在列表中
【发布时间】:2010-09-28 13:36:51
【问题描述】:

如何将委托(命名、匿名、lambda)存储在通用列表中?基本上我正在尝试构建一个委托字典,从中我可以使用一个键访问存储的委托并执行它并按需返回值。可以在 C# 4 中做吗?有什么想法来完成它吗? 注意:在我可以存储任何类型的代表的地方,最好使用异构列表。

【问题讨论】:

  • 注意异构是一个坏主意,你怎么知道你应该传递代表什么参数

标签: c# .net generics delegates lambda


【解决方案1】:

System.Collections.Generic.Dictionary<string, System.Delegate> 还不够吗?

【讨论】:

  • 这样我就不能存储匿名委托或 lambdas。
  • @Anindya Chatterjee:是的,你可以:dic.Add("action", new Action(() => Console.WriteLine("action called!")));
  • 是的,谢谢你提醒我,我完全忘记了 --new Action(() => Console.WriteLine("action called!"))--
【解决方案2】:

好吧,这是一个简单的例子:

class Program
{
    public delegate double MethodDelegate( double a );

    static void Main()
    {
        var delList = new List<MethodDelegate> {Foo, FooBar};


        Console.WriteLine(delList[0](12.34));
        Console.WriteLine(delList[1](16.34));

        Console.ReadLine();
    }

    private static double Foo(double a)
    {
        return Math.Round(a);
    }

    private static double FooBar(double a)
    {
        return Math.Round(a);
    }
}

【讨论】:

  • 我不是在寻找这种解决方案。该解决方案只需要一种特殊的命名委托,而不是其他的。
【解决方案3】:
    public delegate void DoSomething();

    static void Main(string[] args)
    {
        List<DoSomething> lstOfDelegate = new List<DoSomething>();
        int iCnt = 0;
        while (iCnt < 10)
        {
            lstOfDelegate.Add(delegate { Console.WriteLine(iCnt); });
            iCnt++;
        }

        foreach (var item in lstOfDelegate)
        {
            item.Invoke();
        }
        Console.ReadLine();
    }

【讨论】:

    【解决方案4】:
    List<System.Delegate> something;
    something.Add(new Action(()=> DoSomething()));
    

    如果你想自定义key,你可以使用上面的字典

    【讨论】:

      【解决方案5】:
              Dictionary<string, Func<int, int>> fnDict = new Dictionary<string, Func<int, int>>();
              Func<int, int> fn = (a) => a + 1;
              fnDict.Add("1", fn);
              var re = fnDict["1"](5);
      

      【讨论】:

      • 我正在寻找一个对代表没有限制的更通用的解决方案。
      猜你喜欢
      • 2010-10-01
      • 2011-03-05
      • 2020-11-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多