mardi 18 février 2020

How to verify that a Type can be passed to a generic method in C# also restore generic parameter types based on passed arguments

Let me try to explain what I mean. For example I have the following code:

public static class MyClass
{
   public static void DoSmthWithCollection<T>(IEnumerable<T> collection)
   {
       ...
   }
}

Of course, compiler would allow to pass to it an object of List<int> type. Moreover, the compiler will figure out that the type T for the method is resolved to int type based on the argument type.

I need to do the same only dynamically, either by using System.Reflection or Roslyn. Say I get the MethodInfo for the method, I get the generic ParameterInfo. Is there any easy way to figure out that an object of type typeof(List<int>) actually fits to be an argument to the method and that when you pass it, the method resolves T to int type? And I am talking about some relatively easy solution without examining types and subtypes and the generic type constraints. I think at least Roslyn should have one, since this is what the C# compiler is doing.

Thanks for your help.





Aucun commentaire:

Enregistrer un commentaire