【问题标题】:Compiler says I cannot take the address of a value type's readonly field编译器说我不能获取值类型的只读字段的地址
【发布时间】:2013-07-05 07:44:43
【问题描述】:

我有一个结构:

struct S {
    public readonly int Value1;
    public readonly int Value2;
    public S(int value1, int value2) {
        this.Value1 = value1;
        this.Value2 = value2;
    }
}

我尝试获取Value2的地址:

var s = default(S);
unsafe {
    var r = new IntPtr(&s.Value2);
}

但我得到一个编译器错误:

Cannot take the address of the given expression

我以为我可以获取字段的地址?怎么回事?

【问题讨论】:

  • 这是一个类似的问题,但分辨率完全不同。问题是句法,而不是语义。另外,唯一提到readonly 是一个稍微错误的答案,它似乎是在谈论结果是复制性而不是只读性。

标签: c# unsafe value-type addressof


【解决方案1】:

显然它不适用于只读字段。将 S 更改为:

struct S {
    public int Value1;
    public int Value2;
}

解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2013-11-15
    • 2021-12-20
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多