简体   繁体   中英

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.

I can make a direct cast in Inmediate Window but have not found a way to make the cast with F#.

Why cast? You can call GetParameters() and all the other members you'd need on the MethodBase reference.

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

EDIT (return types):

First, note that GetMethod returns MethodInfo, not MethodBase. You can't cast to RuntimeMethodInfo since, as others have noted, that is an internal type. But the ReturnType property is declared on MethodInfo, so all is well.

This therefore works, with the static type of methodInfo being 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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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