gpt4 book ai didi

c# - 如何在构造后修改值类型中的只读字段

转载 作者:行者123 更新时间:2023-12-02 05:13:50 24 4
gpt4 key购买 nike

来自 C# 4.0 第 7.5.5 节。

If M is an instance function member declared in a value-type:

  • [...]
  • If E is not classified as a variable, then a temporary local variable of E's type is created and the value of E is assigned to the variable. E is then reclassified as a reference to that temporary local variable. The temporary variable is accessible as this within M, but not in any other way. Thus, only when E is a true variable (what is a true variable...?) is it possible for the caller to observe the changes that M makes to this.

Eric Lippert 继续说道:

This point illustrates yet another way in which the combination of mutability and copy-by-value semantics can lead to trouble. For example, a readonly field is not classified as a variable after the constructor runs. Therefore, an attempt to call a method that mutates the contents of a readonly field of a value type succeeds but actually mutates a copy! Avoid these problems by avoiding mutable value types altogether.

如何重现 Eric 描述的场景?我尝试了以下。如我所料,它会出错:

    struct A
{
public readonly int mutableReadonlyField;

public A(int originalValue)
{
mutableReadonlyField = originalValue;
}

public A MethodThatMutatesTheContentsOfAReadOnlyField(int mutate)
{
this.mutableReadonlyField = mutate;//Constructor has run so mutableReadonlyField is a temporary local variable
//ERROR: A readonly field cannot be assigned to (except in a constructor or a variable initializer)

A newA = this;//Is this a true variable?
return newA;
}
}

最佳答案

我在我的博客上举了一个例子:

http://ericlippert.com/2008/05/14/mutating-readonly-structs/

问题是我的句子片段“值类型的只读字段”含糊不清且具有误导性。我本意是指 中的只读字段,其中该字段的值类型为 S,但显然更自然的阅读方式是将其视为只读字段 在 S 本身。我应该完全重写这句话。为错误道歉。

回答你的另一个问题:形容词“真”是不必要的。如果只说“因此,只有当 E 是一个变量时,调用者才有可能观察到 M 对此所做的更改,这句话同样正确。”

关于c# - 如何在构造后修改值类型中的只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14960391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com