简体   繁体   English

在F#中将MethodBase转换为RuntimeMethodInfo

[英]Cast MethodBase to RuntimeMethodInfo in F#

I want to cast MethodBase to RuntimeMethodInfo in order to retrieve the name and type of the arguments of reflected methods, and the returned type of those methods. 我想将MethodBase强制转换为RuntimeMethodInfo以便检索反射方法的参数的名称和类型,以及这些方法的返回类型。

I can make a direct cast in Inmediate Window but have not found a way to make the cast with F#. 我可以在“中间窗口”中进行直接转换,但是还没有找到使用F#进行转换的方法。

Why cast? 为什么要投? You can call GetParameters() and all the other members you'd need on the MethodBase reference. 您可以在MethodBase参考上调用GetParameters()以及所需的所有其他成员。

let methodInfo : MethodBase = //whatever
let firstParamName = methodInfo.GetParameters().[0].Name

EDIT (return types): 编辑(返回类型):

First, note that GetMethod returns MethodInfo, not MethodBase. 首先,请注意,GetMethod返回的是MethodInfo,而不是MethodBase。 You can't cast to RuntimeMethodInfo since, as others have noted, that is an internal type. 您不能转换为RuntimeMethodInfo,因为正如其他人所指出的那样,这是一种内部类型。 But the ReturnType property is declared on MethodInfo, so all is well. 但是ReturnType属性是在MethodInfo上声明的,所以一切都很好。

This therefore works, with the static type of methodInfo being MethodInfo: 因此,这是有效的,其中methodInfo的静态类型为MethodInfo:

let methodInfo = typeof<object>.GetMethod("ToString")
let returnTypeName = methodInfo.ReturnType.Name // "String"

Second, if you have a static reference to a MethodBase that you know is a MethodInfo, use the :?> operator. 其次,如果您拥有对MethodBase的静态引用(您知道它是MethodInfo),则使用:?>运算符。 Example: 例:

let toMethodInfo (mb : MethodBase) = mb :?> MethodInfo

On the other hand, if you're not sure about the object's actual type, you can use match : 另一方面,如果不确定对象的实际类型,则可以使用match

let tryToMethodInfo (mb : MethodBase) =
    match mb with
    | :? MethodInfo as result -> Some result
    | _ -> None

Finally, since you ask about "vice versa" in your comment: When you're going from a derived class to one of its base classes, which always succeeds, you don't need the question mark: 最后,由于您在评论中询问“反之亦然”:当您从派生类转到其始终成功的基类之一时,不需要问号:

let toMethodBase (mi : MethodInfo) = mi :> MethodBase

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

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