Question

Currently I am using using action to append some method call as a string. Like below:

var MyAction = new List<Action>();

MyAction.Add(() => this.FunctionA(new string[] { "All" }));
MyAction.Add(() => this.FunctionB(new string[] {"All"}));
MyAction.Add(() => this.FunctionC(new string[] {"-null-"}));

and iterating this action to do some run time processing:

foreach (var action in LoadDSAction)
{
    action();
}

however now I have to call few object creation statements using same approach. e.g:

ClssA objA = new ClsA();
ClssB objB = new ClsB();
ClssC objC = new ClsC();

how to add these in to an action so that I can iterate further?

Was it helpful?

Solution

If I got your intent, instead of Action you need to use delegate which returns some data. E.g. Func<object>:

var factories = new List<Func<object>>();
factories.Add(() => new ClsA());
factories.Add(() => new ClsB());
factories.Add(() => new ClsC());

Then you can create objects in a loop:

foreach(var factory in factories)
{
   var obj = factory();
   //
}

If ClsA, ClsB, ClsC inherit some base type, you can use that type as Func generic type parameter.

OTHER TIPS

not exactly sure what you're trying to achieve but the same pattern will certainly work i.e.

public class ClssA{
    private string id;
    public ClssA(string id)
{
    this.id = id;
    System.Console.WriteLine("I'm {0}", id);
}

then

MyAction.Add(() => new ClssA("One"));
MyAction.Add(() => new ClssA("Two"));
MyAction.Add(() => new ClssA("Three"));

foreach (var action in MyAction)
{
    action();
}

Would instantiate your classes as is evidenced by the output from the constructor:

I'm One
I'm Two
I'm Three
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top