为什么F#引用不能包含struct? [英] Why F# quotation cannot contains struct?
问题描述
我想定义一个结构,其中包含一些成员方法.我想使用[<ReflectedDefinition>]
标记该struct成员方法.但是编译器告诉我这是错误的.
I would like to define a struct, which contains some member methods. And I want to use [<ReflectedDefinition>]
to mark that struct member method. But the compiler tells me it is wrong.
首先,请看这段代码:
type Int4 =
val mutable x : int
val mutable y : int
val mutable z : int
val mutable w : int
[<ReflectedDefinition>]
new (x, y, z, w) = { x = x; y = y; z = z; w = w }
[<ReflectedDefinition>]
member this.Add(a:int) =
this.x <- this.x + a
this.y <- this.y + a
this.z <- this.z + a
this.w <- this.w + a
override this.ToString() = sprintf "(%d,%d,%d,%d)" this.x this.y this.z this.w
它会编译.但是,如果我将类型设为结构,则无法对其进行编译:
It compiles. But if I make the type a struct, it cannot be compiled:
[<Struct>]
type Int4 =
val mutable x : int
val mutable y : int
val mutable z : int
val mutable w : int
[<ReflectedDefinition>]
new (x, y, z, w) = { x = x; y = y; z = z; w = w }
[<ReflectedDefinition>]
member this.Add(a:int) = // <----------- here the 'this' report compile error
this.x <- this.x + a
this.y <- this.y + a
this.z <- this.z + a
this.w <- this.w + a
override this.ToString() = sprintf "(%d,%d,%d,%d)" this.x this.y this.z this.w
我收到以下错误:
error FS0462: Quotations cannot contain this kind of type
在此代码中指向this
.
任何人都知道为什么我不能在struct成员函数上创建引号吗?我猜可能是因为该struct是值类型,所以该指针应该是byref.
Anyone has any idea on why I cannot create quotation on a struct member function? I guess it might because that struct is value type, so this pointer should be byref.
推荐答案
实际上,在F#3.0中观察到的编译器错误为:
In fact, the observed compiler error in F# 3.0 reads:
错误FS1220:ReflectedDefinitionAttribute可能不适用于实例 成员在结构类型上,因为实例成员采用隐式"this" byref参数
error FS1220: ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter
观察到的行为的根本原因是F#引号的限制-您不能在引用的代码中使用byref
类型.
The root cause of the observed behavior is the limitation of F# quotations - you cannot use byref
types in the quoted code.
尽管如此,此限制的结果仅适用于 instance struct
成员; static
struct
成员可以用[<ReflectedDefinition]>
属性修饰.
Nevertheless, the consequence of this limitation is applicable only to the instance struct
members; static
struct
members can be decorated with [<ReflectedDefinition]>
attribute.
这篇关于为什么F#引用不能包含struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!