开发者

c# generic method + reflection question

开发者 https://www.devze.com 2023-01-14 20:24 出处:网络
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.

In C# I want to create a generic method that:

  1. Accepts a MethodInfo object as a parameter.
  2. 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)));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号