How to store delegates in a List

2020-02-06 05:37发布

How can I store delegates (named, anonymous, lambda) in a generic list? Basically I am trying to build a delegate dictionary from where I can access a stored delegate using a key and execute it and return the value on demand. Is it possible to do in C# 4? Any idea to accomplish it? Note : Heterogeneous list is preferable where I can store any kind of delegates.

4条回答
SAY GOODBYE
2楼-- · 2020-02-06 06:17
    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();
    }
查看更多
劳资没心,怎么记你
3楼-- · 2020-02-06 06:18

Well, here's a simple example:

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);
    }
}
查看更多
三岁会撩人
4楼-- · 2020-02-06 06:24

Does System.Collections.Generic.Dictionary<string, System.Delegate> not suffice?

查看更多
贪生不怕死
5楼-- · 2020-02-06 06:33
        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);
查看更多
登录 后发表回答