I have a set of methods that accept type arguments:
public void Process<T>() { ... }
public void Process<T1, T2>() { ... }
public void Process<T1, T2, T3>() { ... }
Inside of these methods, I'm creating workers that execute sequentially, in the order specified by the type arguments, so for example:
public void Process<T1, T2>() {
List<WorkerProcess> workers = GetWorkersFromTypes(typeof(T1), typeof(T2));
if (workers?.Count > 0)
foreach (var worker in workers)
if (worker != null)
worker.Process();
}
public List<WorkerProcess> GetWorkersFromTypes(params Type[] workerTypes) {
var workers = new List<WorkerProcess>();
foreach (var type in types) {
if (type == typeof(WorkerA))
workers.Add(new WorkerA());
else if (type == typeof(WorkerB))
workers.Add(new WorkerB());
}
return workers;
}
While this is effective, it's rather verbose using the typeof
keyword. I'm wondering if there's something similar for type arguments that would enable something like this instead:
public void Process<T1, T2>() {
List<WorkerProcess> workers = GetWorkersFromTypes<T1, T2>();
...
}
public List<WorkerProcess> GetWorkersFromTypes<params T[] types>() { ... }
In all my research, I'm coming to the conclusion that it is not possible, but there are much smarter and more effective researchers here that might be able to prove otherwise.
Is there a way to get infinite type arguments, in a manner similar to the params
keyword, in C#?