Why C# will allow this :
public class MyClass
{
static int A=1;
static int B=A+1;
}
But won't allow ("A field initializer cannot reference the non-static field, method, or property") this
public class MyClass
{
int A=1;
int B=A+1;
}
I thought that it's the order that is guaranteed (with static fields) to be sequential initialized as it appears , but it's also applied here as you can see :
public class MyClass
{
int A=((Func<int>)(delegate(){ Console.WriteLine ("A"); return 1;}))();
int B=((Func<int>)(delegate(){ Console.WriteLine ("B"); return 2;}))();
int C=((Func<int>)(delegate(){ Console.WriteLine ("C"); return 3;}))();
}
void Main()
{
var a = new MyClass();
}
Result :
A
B
C
Question
I'm more interested with the reason/logic for why it was restricted. just for curiosity.
nb didn't find any duplicate.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…