代码检查:从 'readonly' 成员调用非只读成员会导致 'this' 的隐式复制
此检查会报告从 readonly 结构体成员调用另一个不是 readonly 的实例成员的情况。 该调用会强制编译器对 this 进行隐式复制。 之后的任何修改都发生在副本上,即使没有修改,额外的防御性副本仍然可能令人惊讶或导致低效。
示例
struct S
{
public int Value;
public int GetValue()
{
return Value;
}
public readonly int Read()
{
return GetValue();
}
}
struct S
{
public int Value;
public readonly int GetValue()
{
return Value;
}
public readonly int Read()
{
return GetValue();
}
}
快速修复
根据具体情况,快速修复可以将被调用成员设为 readonly ,或从包含成员中移除 readonly。
2026年 5月 8日