lundi 27 avril 2015

How do you call GetMethod for a generic function that takes a generic parameter?

I know I can fetch the method info using GetMethods, but I want to know how to do it properly without GetMethods. I have read other SO questions and answers that suggest this is not possible, or suggest just using LINQ instead, but that isn't really an answer to the question.

Consider at the most basic level, a static generic function that takes a single generic parameter.

private static void Test<T>(T val)
{
}

To fetch this method info we can just call Type.GetMethod("Test", BindingFlags.Static | BindingFlags.NonPublic). However if there were some reason we could not use this simple GetMethod signature (perhaps due to multiple overloads), then we need to supply the parameter types. The problem is that I cannot create a parameter type that accurately matches the T val parameter. What's interesting is that I can take the parameters from the method info (fetched with GetMethods) and pass that into GetMethod to get the desired outcome. This means that if it were only possible to create the appropriate generic types (with IsGenericParameter set to true) then I feel like this would be completely possible.

So that means that this is entirely possible in .NET, and only require the creation of the proper type instances. How does one create these type instances? And if they are not possible to create, why aren't they?

I created a simple fiddle to showcase the issue.





Aucun commentaire:

Enregistrer un commentaire