2013-04-11 49 views
3

我想定义一个结构体,其中包含一些成员方法。我想用[<ReflectedDefinition>]来标记该结构成员方法。但编译器告诉我这是错误的。为什么F#语句不能包含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) = 
     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 

它编译。但是,如果我做的类型结构,它不能被编译:

[<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成员函数的引号?我想这可能是因为该结构是值类型,所以这个指针应该是byref。

+0

@JohnPalmer感谢您的语法编辑:) – 2013-04-11 03:51:31

回答

3

事实上,在F#3.0中观察到的编译器错误读取:

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类型。

尽管如此,此限制的后果仅适用于实例struct成员; staticstruct会员可以用[<ReflectedDefinition]>属性进行装饰。

相关问题