Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top