Generics 如何将System.Reflection.MemberInfo值转换为它表示的F值?
我试图在运行时加载并执行F#代码。Generics 如何将System.Reflection.MemberInfo值转换为它表示的F值?,generics,reflection,f#,system.reflection,Generics,Reflection,F#,System.reflection,我试图在运行时加载并执行F#代码。FSharp.Compiler.Service程序集为程序中的每个值(或函数)定义生成System.Reflection.MemberInfo值 我大致尝试实现以下内容: cast<'a> : System.Reflection.MemberInfo -> 'a cast首先,您的函数需要有一个可选的结果,以表明它可能并不总是成功的 然后,成员可以是(a)嵌套类型、(b)属性、(c)字段和(d)方法。我猜你只对后三个感兴趣 你需要分别处理这三
FSharp.Compiler.Service
程序集为程序中的每个值(或函数)定义生成System.Reflection.MemberInfo
值
我大致尝试实现以下内容:
cast<'a> : System.Reflection.MemberInfo -> 'a
cast首先,您的函数需要有一个可选的结果,以表明它可能并不总是成功的
然后,成员可以是(a)嵌套类型、(b)属性、(c)字段和(d)方法。我猜你只对后三个感兴趣
你需要分别处理这三种情况,因为它们实际上是不同的东西,而不是三种相同的东西。对于字段和属性,可以分别使用FieldInfo.GetValue
和PropertyInfo.GetValue
来获取值。对于方法,可以使用MethodInfo.Invoke
调用它并返回结果
大致:
let getValue<'a> (o: obj) (m: MemberInfo): 'a option =
match m with
| :? FieldInfo as f when f.FieldType = typeof<'a> ->
Some( f.GetValue o :?> 'a )
| :? PropertyInfo as p when p.PropertyType = typeof<'a> && p.GetIndexParameters().Length = 0 ->
Some( p.GetValue( o, [||] ) :?> 'a )
| _ -> None
let getFunc<'a, 'b> (o: obj) (m: MemberInfo): ('a -> 'b) option =
match m with
// F# compiler may compile some functions as properties of type FSharpFunc<_>, so need to cover that
| :? FieldInfo -> getValue<'a -> 'b> o m
| :? PropertyInfo -> getValue<'a -> 'b> o m
// If it's a real method of the right type, create a closure to call it
| :? MethodInfo as mt
when mt.ReturnType = typeof<'b> &&
mt.GetParameters().Length = 1 &&
mt.GetParameters().[0].ParameterType = typeof<'a> ->
Some <| fun (a: 'a) -> mt.Invoke( o, [| a :> obj |] ) :?> 'b
// Otherwise, can't produce result
| _ -> None
让getValue无
让getFunc(o:obj)(m:MemberInfo):('a->'b)选项=
匹配
//F#编译器可能会将某些函数编译为FSharpFunc类型的属性,因此需要涵盖这一点
| :? FieldInfo->getValue o m
| :? PropertyInfo->getValue o m
//如果它是正确类型的真实方法,请创建一个闭包来调用它
| :? MethodInfo作为mt
当mt.ReturnType=typeof->
有些情况下,您需要提供调用成员的对象。或者你只对静态成员感兴趣?