In C# I want to create a generic method that:
- Accepts a MethodInfo object as a parameter.
- Returns the objec开发者_运维问答t that is returned when the MethodInfo is invoked.
The source of my confusion is that I want the method to be generically typed to the same return type as the MethodInfo object that gets passed in.
You cannot do this. By definition, generics are a compile-time construct, while the return type of a particular MethodInfo
is something that is only known at runtime (when you receive a specific MethodInfo
instance), and will change from call to call.
Pavel Minaev is right,
My suggestion in this case (of course i don't know the whole context) is use a method that returns a dynamic type, of course is that wouldn't be typed.
public dynamic MyMethod(MethodInfo methodInfo)
Or since you know what is the return type, put that in the method call:
public T MyMethod<T>(MethodInfo methodInfo)
of course you gonna get in trouble inside the method mapping the conversions. but you can also put the conversion in a parameter using lambda, like:
public T MyMethod<T>(MethodInfo methodInfo, Func<object, T> conversion)
i think the call of the method will be very clear, like:
Console.WriteLine(MyMethod(methodInfo, (a) => Convert.ToString(a)));
精彩评论