There is a class, such as

public class MyClass { public void Method1(params) { } public void Method2(params) { } public void Method3(params) { } } 

Then somewhere in the code, at the request of the user, methods are called from one of the instances in an arbitrary order. The user clicked the desired button, the method was executed.

 theMyClass.Method1(params); theMyClass.Method2(params); theMyClass.Method1(params); theMyClass.Method3(params); ***** 

This should be stored somewhere so that it is possible to perform the same methods in the same order for another instance of the class MyClass .

I suspect that you need to save the commands in the queue, and then execute them with another parameter. But before I implement it, I would like to know if there are other ways?

  • one
    Read about the Command pattern, in my opinion, this is just your topic - qzavyer
  • one
    @qzavyer, read to the end, please - iRumba
  • There is a way through Reflection.MethodBase to store a link to the method, object, and an array of parameters for Invoke(object , params[] ) - nick_n_a

1 answer 1

For example, something like this:

 class MethodPack { List<Action<MyClass>> methods = new List<Action<MyClass>>(); public void Add(Action<MyClass> a) => methods.Add(a); public void Execute(MyClass obj) { foreach (var method in methods) method(obj); } } 

Now your button should run this code:

 MethodPack pack = new MethodPack(); MyClass firstObj = new MyClass(); void CallThisForButtonA() { Action<MyClass> a = obj => obj.Method1(1, 2, 3); pack.Add(a); a(firstObj); } void CallThisForButtonB() { Action<MyClass> a = obj => obj.Method2(6, "ромашка", 7); pack.Add(a); a(firstObj); } 

and so on.

When you need to apply a sequence to another instance, write:

 MyClass secondObj = ...; pack.Execute(secondObj); 

(Yes, the MethodPack class can be generalized.)

  • I did not understand something. What does this line do? Action<MyClass> a = obj => obj.Method1(1, 2, 3); - iRumba
  • @iRumba: It creates a function that executes the obj.Method1(1, 2, 3) code obj.Method1(1, 2, 3) MyClass obj object. And puts this function in the variable a . - VladD
  • Well, yes, all the same with the teams will be more beautiful ... Although it should work faster - iRumba
  • @iRumba: How would it be with the teams? I could not think of something. - VladD
  • I was on vacation :) Well, the team is a copy of the class. This means that the team can be shoved into the collection (queue) and executed at any time, anywhere, by calling it Executed with the necessary parameters. How and where to store these parameters depends on the specific task. If these methods are in view of a model (reaction to user actions), then everything is generally simple. Practical implementation - macro recording. And if these are the methods of the model, it is more difficult, but also solvable. since I am interested in the first option, I don’t want to think about the second one yet. - iRumba