gpt4 book ai didi

c# - 'A field initializer cannot reference the non-static field, method, or property' CS0236 错误的概念原因

转载 作者:太空狗 更新时间:2023-10-29 21:30:43 42 4
gpt4 key购买 nike

C# 不允许实例字段初始化程序 引用另一个字段。例如,此代码无效:

class A
{
string s1 = "";
string s2 = s1;
}

因为“s2”引用了“s1”。

但为什么不允许这样做呢?

我的第一个想法是 C# 规范 不保证任何初始化顺序,但根据规范,该顺序是声明的顺序:

The variable initializers are executed in the textual order in which they appear in the class declaration.

那么,如果顺序是确定性的,那么这种代码的陷阱是什么?

预先感谢您的帮助。

编辑:

根据 Hps0xA3Peter 的回答:

  • 继承场景中的初始化顺序可能会很困惑,

  • 实现这样的功能需要编译器开发团队的一些资源,但收效甚微,

  • 出于逻辑原因不可能使用方法或属性(感谢 Peter),因此为了保持一致性,字段也是如此。

最佳答案

我不确定字段,但拒绝字段初始值设定项访问属性或方法似乎是合理的。例如:

class A
{
string s1 = GetString();
string s2 = this.MyString;
string s3 = "test";

public string GetString()
{
// this method could use resources that haven't been initialized yet
}

public string MyString
{
get { return s3; }
// this field hasn't been initialized yet
// (okay, strings have a default value, but you get the picture)
}
}

关于c# - 'A field initializer cannot reference the non-static field, method, or property' CS0236 错误的概念原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4285921/

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