【问题标题】:Why F# quotation cannot contains struct?为什么 F# 引用不能包含结构?
【发布时间】:2013-04-11 02:37:23
【问题描述】:

我想定义一个结构,其中包含一些成员方法。我想使用[<ReflectedDefinition>] 来标记该结构成员方法。但是编译器告诉我这是错误的。

首先,看这段代码:

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

有人知道为什么我不能在结构成员函数上创建引号吗?我猜可能是因为该结构是值类型,所以这个指针应该是 byref。

【问题讨论】:

  • @JohnPalmer 感谢您的语法编辑 :)

标签: f#


【解决方案1】:

实际上,在 F# 3.0 中观察到的编译器错误为:

错误 FS1220:ReflectedDefinitionAttribute 可能未应用于实例 结构类型上的成员,因为实例成员采用隐式“this” byref 参数

观察到的行为的根本原因是 F# 引用的限制 - 您不能在引用的代码中使用 byref 类型。

不过,此限制的后果仅适用于 instance struct 成员; staticstruct 成员可以用[&lt;ReflectedDefinition]&gt; 属性修饰。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多