gpt4 book ai didi

c# - 静态属性的总和不正确

转载 作者:太空狗 更新时间:2023-10-30 00:08:14 26 4
gpt4 key购买 nike

我有这样一个小类:

private static int field1 = - 1;
private static int field2 = field1 + 1;

public static void Sum()
{
field1 = 10;
Debug.WriteLine(field2);
}

调用 Sum() 会写入“0”。为什么?

最佳答案

那些不是属性——它们是字段。 field2 在初始化时与 field1 相关 - 之后,它们是完全独立的字段。这不像每次读取 field2 或每次写入 field1 时都重新评估 field1 + 1 表达式。

如果您希望 field2 仅依赖于field1 的值,您应该将其设为属性:

// Note: I wouldn't actually call this Field2, of course...
private static int Field2 { get { return field1 + 1; } }

关于c# - 静态属性的总和不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047679/

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