-2

I have the following Method:

void Register<T> where T : class {
   _myList.Add(typeof(T))
}

Where _myList is a List<Type>.

I now want to call a generic class for each Type:

 cfg.ReceiveEndpoint("MyTestQueue", ec => {
  _myList.ForEach(t => ec.ConfigureConsumer<GenericConsumer<typeof(T)>>(context);
});

Any idea how I can do that ?

Ben D
  • 465
  • 1
  • 6
  • 20
  • 2
    There are hundreds of duplicates, blog posts, whatever you can think of. Please try to do a bit of research next time. As a bit extra help, you can (and should) search like this in the future: `c# generic from type site:stackoverflow.com` – Camilo Terevinto Jan 04 '21 at 21:16
  • It's not the same issue, I've udpated the question – Ben D Jan 05 '21 at 09:33
  • Can you edit your question with more details, please? The linked questions demonstrate the use of `MakeGenericType` and `MakeGenericMethod`, which are all you need to solve this problem. – ProgrammingLlama Jan 05 '21 at 09:39
  • @BenD It's still the exact same issue. You need to call `ec.ConfigureConsumer` through Reflection – Camilo Terevinto Jan 05 '21 at 11:14

1 Answers1

1

Instead of saving the Type you could save a delegate to MyGeneric<T>, like:

List<Action> _myList = new List<Action>();

void Register<T>() where T : class
{
    _myList.Add(() => MyGeneric<T>());
}

void MyGeneric<T>()
{
    Console.WriteLine($"Running MyGeneric<{typeof(T)}>");
}
    
void Run()
{
    foreach (var del in _myList)
    {
        del();
    }
}

and then:

Register<string>();
Register<int[]>();

Run();

Result:

Running MyGeneric<System.String>
Running MyGeneric<System.Int32[]>
xanatos
  • 109,618
  • 12
  • 197
  • 280