samedi 9 février 2019

How to find the matching MethodInfo from only name and specific arguments?

I need to get a specific method from a type given only the name and the specific parameters. (and of course the containing type)

static MethodInfo ResolveMethod(Type type, string name, Type[] arguments) { }

I tried type.GetMethod() but it will never find generic methods (as you have to instantiate them through MakeGenericMethod)

There is also Type.MakeGenericParameter() but that only exists in .net core, and I target .net framework.

I thought about how I could implement this method and came up with one initially promising way that didn't work out:

Initially I would of course get all methods where the name and number of parameters matches. Then I would inspect each argument to see if it could be instantiated into the given argument type.

And that's where I didn't know how to progress, because even if I would be able to decide that the generic T would be an int for example, then I would somehow still need to find all the other locations where the same T is used in the method signature and check if I can put an int in there as well.

And everything gets even harder when there are multiple methods that could potentially be instantiated so they accept the given parameters (like one takes T as first arg, one takes IEnumerable, and one takes object). In that case the match would be ambigous I guess. But I want to find the best match in that case.

While it is obvious that this problem is definitely solvable because the c# compiler solves the exact same problem with inputs that are just as limited (it only knows the argument types that are being passed, and it has to decide which overload to use), I can't seem to find a way to do it.

Actually, my case is a little easier even because I know that the arguments I'm given will always be fully specified / concrete types. They might be generic with multiple levels (like an expression containing a func containing a list,....) but at least they are always "closed".





Aucun commentaire:

Enregistrer un commentaire