I want to create a list of methods to execute. Each method has the same signature. I thought about putting delegates in a generic collection, but I keep getting this error:
'method' is a 'variable' but is used like a 'method'
In theory, here is what I would like to do:
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);
}
Any ideas on how to accomplish this? Thanks!
You need to cast the object
in the list to a BinaryOp
, or, better, use a more specific type parameter for the list:
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);
}
Using .NET 3.0 (or 3.5?) you have generic delegates.
Try this:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With