General class with dynamic number of types

I don’t know how to formulate this question without using an example, so here we go ...

I defined a class like this:

public class Orchestration<T1, T2, T3> { 

Using this constructor:

 public Orchestration(Action<T1, T2, T3> action, int maxNumberOfRetries) 

And a method called Run:

 public bool Run(T1 one, T2 two, T3 three) 

Now if I do this:

 var orchestration = new Orchestration<string, string, bool>(File.Copy, 5); orchestration.Run("c:\filename.txt", "d:\filename.txt", true) 

then the orchestration will try to run File.Copy 5 times before it returns false, which means that the task failed (the background here is that I tried to save som files from a disk that was working just now, and then)

The Orchestration class is general, and I can use it to run any method that has three parameters.

My question is: Can I define an orchestration class so that the number of parameters is not predefined?

My goal then would be to let it run any method, not just methods that take three parameters ...

+6
source share
3 answers

Just accept Action and close all the options that you have for your actual method:

 public Orchestration(Action action, int maxNumberOfRetries) 

 var orchestration = new Orchestration( () => File.Copy("c:\filename.txt", "d:\filename.txt", true), 5); 

This means knowing the parameter values ​​when building, not when calling Run , but in this context, this does not seem like a problem that you cannot solve.

+6
source

There is no way to do this using generics in C #. This will require something similar to variable templates in C ++ , but in a controlled world there are no equal. Therefore, for classes such as Tuple , there are so many different classes using factory methods to create different versions.

If your parameters were either not general (i.e.: object ) or always a string, you can use params to allow a variable number of arguments.

+9
source

No, you cannot do this.

Take a look at Tuple s, Action and Func in the .NET API ... they should create a version of each of these common classes that takes 1 type argument, which takes 2 type arguments, etc. etc.

If you want something cool, try the following:

 static class Extensions { public static TimesDo( this int x, Action action) { for (int i = 0; i < x; i++) action.Invoke(); } } 

Then:

 int x = 4; x.TimesDo(() => { File.Copy( .... ) } ); 

or

 (5).TimesDo(() => { File.Copy( .... ) }); 
0
source

All Articles