为什么C#不允许与非静态字段字段初始值? [英] Why C# won't allow field initializer with non-static fields?

查看:190
本文介绍了为什么C#不允许与非静态字段字段初始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C#将允许这样的:

 公共类MyClass的
{
  静态INT A = 1;
  静态INT B = A + 1;
}

但不会允许(一个字段初始不能引用非静态字段,方法或属性的)这个

 公共类MyClass的
{
   INT A = 1;
   INT B = A + 1;
}

我认为它是的为了的这是保证(静态字段)是连续的初始化为出现,但的它也是在这里的,你可以看到应用:

 公共类MyClass的
{
   INT A =((Func键< INT>)(委托(){Console.WriteLine(A);返回1;}))();
   INT B =((Func键&所述; INT&GT)(委托(){Console.WriteLine(B);返回2;}))();
   INT C =((Func键< INT>)(委托(){Console.WriteLine(C);返回3;}))();
}无效的主要()
{
 VAR一个=新MyClass的();
}

结果:

  A

C

我用的理由/逻辑更感兴趣的它为什么受到限制。只是出于好奇。

NB没有发现任何重复的。


解决方案

  

我与它为什么被限制的原因/逻辑更感兴趣。只是出于好奇。


如果你读了C#语言规格,10.11.3,它提示为这里的理由。在讨论的变量初始化的:


  

想实例变量初始化函数和构造函数初始化的作为是在构造函数体之前自动插入语句是有用的。


由于这些是构造之前插入,他们正在为前执行该是有效的,所以让你参考其他成员(有效这个)将有问题的。

请注意,这是与静态字段如何工作的,以及一致的。在这两种情况下,你的允许访问的静态数据,而不是实例数据。您会收到错误消息(A字段初始不能引用非静态字段,方法或属性)直接指出这一点。

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.

解决方案

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.

这篇关于为什么C#不允许与非静态字段字段初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆