How to store delegates in a List

2020-02-06 06:00发布

问题:

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.

回答1:

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



回答2:

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


回答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:

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