如何以编程方式在 F# 中构建以下引用表达式?
How do I programmatically build up the following Quotation Expression in F#?
我需要在引号表达式中访问 .NET 字典。以下是简化版:
let mutable dict:Dictionary<string, float> = Dictionary()
dict.Add("first", 1.0)
dict.Add("second", 2.0)
let qe2 = <@ dict.["second"] @>
qe2的输出结果如下:
val qe2 : Quotations.Expr<float> =
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("second")])
当我可以直接用上面引用的代码直接创建引用表达式时,一切都很好。我如何通过以编程方式构建 qe2
来实现相同的目的?
我知道我需要以某种方式以嵌套方式使用 Quotations.Expr.PropertyGet
两次,但我不知道如何获得必要的 PropertyInfo and MethodInfo
对象来执行此操作。
关键是要知道 let dict
声明在静态模块 class.
上被编译为一个 属性
这是一个工作示例。
module QuotationsTest
open Microsoft.FSharp.Quotations
open System
open System.Collections.Generic
open System.Reflection
let mutable dict:Dictionary<string, float> = Dictionary()
dict.Add("first", 1.0)
dict.Add("second", 2.0)
let qe2 = <@ dict.["second"] @>
let moduleType = Type.GetType("QuotationsTest")
let dictProp = moduleType.GetProperty("dict", BindingFlags.Static ||| BindingFlags.Public)
let indxProp = dict.GetType().GetProperty("Item", [| typeof<string> |])
let qe1 = Expr.PropertyGet(Expr.PropertyGet(dictProp, []), indxProp, [ Expr.Value("first") ])
printfn "%A" qe1
printfn "%A" qe2
编译并运行以上结果如下:
> fsc QuotationsTest.fs
Microsoft (R) F# Compiler version 12.0.30815.0
Copyright (c) Microsoft Corporation. All Rights Reserved.
> QuotationsTest.exe
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("first")])
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("second")])
我需要在引号表达式中访问 .NET 字典。以下是简化版:
let mutable dict:Dictionary<string, float> = Dictionary()
dict.Add("first", 1.0)
dict.Add("second", 2.0)
let qe2 = <@ dict.["second"] @>
qe2的输出结果如下:
val qe2 : Quotations.Expr<float> =
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("second")])
当我可以直接用上面引用的代码直接创建引用表达式时,一切都很好。我如何通过以编程方式构建 qe2
来实现相同的目的?
我知道我需要以某种方式以嵌套方式使用 Quotations.Expr.PropertyGet
两次,但我不知道如何获得必要的 PropertyInfo and MethodInfo
对象来执行此操作。
关键是要知道 let dict
声明在静态模块 class.
这是一个工作示例。
module QuotationsTest
open Microsoft.FSharp.Quotations
open System
open System.Collections.Generic
open System.Reflection
let mutable dict:Dictionary<string, float> = Dictionary()
dict.Add("first", 1.0)
dict.Add("second", 2.0)
let qe2 = <@ dict.["second"] @>
let moduleType = Type.GetType("QuotationsTest")
let dictProp = moduleType.GetProperty("dict", BindingFlags.Static ||| BindingFlags.Public)
let indxProp = dict.GetType().GetProperty("Item", [| typeof<string> |])
let qe1 = Expr.PropertyGet(Expr.PropertyGet(dictProp, []), indxProp, [ Expr.Value("first") ])
printfn "%A" qe1
printfn "%A" qe2
编译并运行以上结果如下:
> fsc QuotationsTest.fs
Microsoft (R) F# Compiler version 12.0.30815.0
Copyright (c) Microsoft Corporation. All Rights Reserved.
> QuotationsTest.exe
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("first")])
PropertyGet (Some (PropertyGet (None, dict, [])), Item, [Value ("second")])