F#-手工创建Expr
我正在尝试创建一个F#-手工创建Expr,f#,F#,我正在尝试创建一个Expr= 设p=E.参数(typeof>(p) 这将产生: Expression string>使用Expr模块?C#示例有点可疑,如果调用buildExpression,则结果将是一个表达式(在C#sytnax中):Func(x=>x),它有一个错误的类型。我想C#在构造时不会检查类型,但如果您尝试编译它,它可能会崩溃 我猜您想要构建类似x=>x.Foo的东西。那么下面的代码片段应该可以实现这一点: open Microsoft.FSharp.Quotations ty
Expr=
设p=E.参数(typeof>(p)
这将产生:
Expression string>
使用Expr
模块?C#示例有点可疑,如果调用buildExpression
,则结果将是一个表达式(在C#sytnax中):Func(x=>x)
,它有一个错误的类型。我想C#在构造时不会检查类型,但如果您尝试编译它,它可能会崩溃
我猜您想要构建类似x=>x.Foo
的东西。那么下面的代码片段应该可以实现这一点:
open Microsoft.FSharp.Quotations
type Foo() =
member x.Prop = "hello"
// Create a new variable 'x'
let arg = Var.Global("x", typeof<Foo>)
// Use Reflection to get information about the 'Prop' member
let propInfo = typeof<Foo>.GetProperty("Prop")
// Create a lambda 'fun x -> x.Prop'
let e = Expr.Lambda(arg, Expr.PropertyGet(Expr.Var(arg), propInfo))
打开Microsoft.FSharp.quotes
Foo()类型=
成员x.Prop=“你好”
//创建新变量“x”
设arg=Var.Global(“x”,typeof)
//使用反射获取有关“Prop”成员的信息
让propInfo=typeof.GetProperty(“Prop”)
//创建一个lambda'fun x->x.Prop'
设e=Expr.Lambda(arg,Expr.PropertyGet(Expr.Var(arg),propInfo))
Perfect!e
将返回Expr
在您的示例中,如何让它返回Expr string>
?Expr.Cast
应该这样做。但是要小心!您可以将
强制转换为Expr
,并且错误只会在运行时出现(而不是在编译期间)。
open Microsoft.FSharp.Quotations
type Foo() =
member x.Prop = "hello"
// Create a new variable 'x'
let arg = Var.Global("x", typeof<Foo>)
// Use Reflection to get information about the 'Prop' member
let propInfo = typeof<Foo>.GetProperty("Prop")
// Create a lambda 'fun x -> x.Prop'
let e = Expr.Lambda(arg, Expr.PropertyGet(Expr.Var(arg), propInfo))