简体   繁体   English

C#泛型方法+反射问题

[英]c# generic method + reflection question

In C# I want to create a generic method that: 在C#中,我想创建一个通用方法,该方法是:

  1. Accepts a MethodInfo object as a parameter. 接受MethodInfo对象作为参数。
  2. Returns the object that is returned when the MethodInfo is invoked. 返回调用MethodInfo时返回的对象。

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. 我感到困惑的原因是,我希望该方法的类型通常与传入的MethodInfo对象的返回类型相同。

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. 根据定义,泛型是编译时的构造,而特定MethodInfo的返回类型只有在运行时(当您收到特定MethodInfo实例时)才知道,并且在调用之间会有所不同。

Pavel Minaev is right, 帕维尔·米纳耶夫(Pavel Minaev)是对的,

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: 但您也可以使用lambda将转换放入参数中,例如:

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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM