Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

language design - Why C# won't allow field initializer with non-static fields?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm more interested with the reason/logic for why it was restricted. just for curiosity.

If you read the C# Language Spec, 10.11.3, it hints as to the rationale here. In discussing variable initializers:

It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body.

Since these are "inserted before the constructor", they are being executed prior to this being valid, so allowing you to refer to other members (effectively this) would be problematic.

Note that this is consistent with how static fields work, as well. In both cases, you are allowed to access static data, but not instance data. The error message you receive ("A field initializer cannot reference the non-static field, method, or property") directly notes this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...