[英]Cast MethodBase to RuntimeMethodInfo in F#
我想將MethodBase強制轉換為RuntimeMethodInfo以便檢索反射方法的參數的名稱和類型,以及這些方法的返回類型。
我可以在“中間窗口”中進行直接轉換,但是還沒有找到使用F#進行轉換的方法。
為什么要投? 您可以在MethodBase參考上調用GetParameters()以及所需的所有其他成員。
let methodInfo : MethodBase = //whatever
let firstParamName = methodInfo.GetParameters().[0].Name
編輯(返回類型):
首先,請注意,GetMethod返回的是MethodInfo,而不是MethodBase。 您不能轉換為RuntimeMethodInfo,因為正如其他人所指出的那樣,這是一種內部類型。 但是ReturnType
屬性是在MethodInfo上聲明的,所以一切都很好。
因此,這是有效的,其中methodInfo的靜態類型為MethodInfo:
let methodInfo = typeof<object>.GetMethod("ToString")
let returnTypeName = methodInfo.ReturnType.Name // "String"
其次,如果您擁有對MethodBase的靜態引用(您知道它是MethodInfo),則使用:?>
運算符。 例:
let toMethodInfo (mb : MethodBase) = mb :?> MethodInfo
另一方面,如果不確定對象的實際類型,則可以使用match
:
let tryToMethodInfo (mb : MethodBase) =
match mb with
| :? MethodInfo as result -> Some result
| _ -> None
最后,由於您在評論中詢問“反之亦然”:當您從派生類轉到其始終成功的基類之一時,不需要問號:
let toMethodBase (mi : MethodInfo) = mi :> MethodBase
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.