3

いくつかのメンバー メソッドを含む構造体を定義したいと思います。[<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である必要があるためだと思います。

4

1 に答える 1

3

実際、F# 3.0 で観察されたコンパイラ エラーは次のとおりです。

エラー FS1220: ReflectedDefinitionAttribute は構造体型のインスタンス メンバーに適用されない可能性があります。これは、インスタンス メンバーが暗黙の 'this' byref パラメーターを取るためです。

byref観察された動作の根本的な原因は、F# の引用の制限です。引用されたコードでは型を使用できません。

ただし、この制限の結果は、インスタンス structメンバーにのみ適用されます。static structメンバーは属性で装飾でき[<ReflectedDefinition]>ます。

于 2013-04-11T05:20:52.307 に答える