How to store delegates in a List
32,098
Solution 1
Does System.Collections.Generic.Dictionary<string, System.Delegate>
not suffice?
Solution 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);
}
}
Solution 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();
}
Author by
Anindya Chatterjee
I supposed to know something about Computer and its science, but the reality is I know nothing !!!
Updated on July 09, 2022Comments
-
Anindya Chatterjee almost 2 years
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.
-
Anindya Chatterjee over 13 yearsthat way I can't store anonymous delegates or lambdas.
-
ssss over 13 years@Anindya Chatterjee: Yes, you can:
dic.Add("action", new Action(() => Console.WriteLine("action called!")));
-
Anindya Chatterjee over 13 yearsI am not searching for this kind of solution. The solution only takes a special kind of named delegate, not others.
-
Anindya Chatterjee over 13 yearsI am searching for a more generic solution where there is no constraints for the delegates.
-
Anindya Chatterjee over 13 yearsYa, thanks for reminding me, I totally forgot about --new Action(() => Console.WriteLine("action called!"))--