访问外部程序集中的结构的公共只读成员

Gab*_*iel 6 f# struct member readonly immutability

当我使用F#读取public readonlyC#程序集中定义的结构类型的成员时,我遇到了一个奇怪的错误.

// C#: compile to Lib.dll
namespace Lib
{
    public class MyClass { public readonly int ReadonlyFoo; }

    public struct MyStruct
    {
        public readonly int ReadonlyFoo;
        public int WriteableFoo;
    }
}

// F#: compile to Client.exe
open Lib
let myClass = new MyClass()
printfn "MyClass.ReadonlyFoo = %x" myClass.ReadonlyFoo

let myStruct = new MyStruct()
printfn "MyStruct.WriteableFoo = %x" myStruct.WriteableFoo
printfn "MyStruct.ReadonlyFoo = %x" myStruct.ReadonlyFoo
Run Code Online (Sandbox Code Playgroud)

当我使用F#1.9.6.16编译Client.exe时,最后一行给出错误:

"The address of the variable 'copyOfStruct' may not be used at this point"
Run Code Online (Sandbox Code Playgroud)

截至撰写本文时,网络毫无用处.看起来奇怪的是,人们可以读取类的不可变成员,并且可以读取结构的可变成员,但是无法读取结构的不可变成员.解决方法很简单,但我很好奇:这是编译器中的错误吗?

编辑:我向fsbugs@microsoft.com提交了一份错误报告

Chr*_*ith 3

通常,当人们说“它看起来像是编译器中的错误”时,实际上是“我不知道我在做什么”的代码。然而,在这种情况下,它看起来确实像一个错误。

F# 编译器在幕后制作结构的副本,以防结构发生变异。(这就是为什么即使您定义了一个具有可变字段的结构,您也必须先将该结构的实例属性设置为可变,然后才能更新其字段。) 似乎幕后发生的特殊魔法忘记了“只读”结构字段。

虽然互联网和 StackOverflow 是寻求有关 F# 相关问题的帮助的好地方,但请务必通过电子邮件 fsbugs@microsoft.com 让 F# 团队了解您发现的任何错误