[英]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
声明被编译为静态模块类的属性。
这是一个工作示例。
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")])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.