实例的初始化字段与局部变量字段、初始化、变量、局部

2023-09-02 11:47:19 作者:就是~拽着不放

我一直想知道为什么在下面的例子中它是确定的不可以初始化实例字段(依靠这将有它的默认值),并对其进行访问,而局部变量显然必须被初始化,即使我把它初始化为默认值,它会得到反正...

 公共类识别TestClass
  {
    私人布尔一个;

    公共无效DO()
    {
      布尔B: //这将解决这个问题:= FALSE;
      Console.WriteLine(一);
      Console.WriteLine(B); //使用未分配的局部变量'B'
    }
  }
 

解决方案

有关局部变量,编译器的流量是一个好主意 -​​ 它可以看到一个读变量和写的变量,并证明(在大多数情况下),第一个写操作将第一次读之前发生的。

error C4700 使用了未初始化的局部变量 x

这是不是与实例变量的情况。考虑一个简单的属性 - 你怎么知道,如果有人将其设置才得到它?这使得它基本上是不可行的执行合理的规则 - 所以要么你必须确保的所有的领域是在构造函数中设置,或让他们有默认值。 C#的团队选择了后一种策略。

I have always been wondering about why in the following example it is OK to not initialize the instance field (relying that it will have its default value) and accessing it, while local variables apparently must be initialized, even if I initialize it to default value it would get anyway...

  public class TestClass
  {
    private bool a;

    public void Do()
    {
      bool b; // That would solve the problem: = false;
      Console.WriteLine(a);
      Console.WriteLine(b); //Use of unassigned local variable 'b'
    }
  }

解决方案

For local variables, the compiler has a good idea of the flow - it can see a "read" of the variable and a "write" of the variable, and prove (in most cases) that the first write will happen before the first read.

This isn't the case with instance variables. Consider a simple property - how do you know if someone will set it before they get it? That makes it basically infeasible to enforce sensible rules - so either you'd have to ensure that all fields were set in the constructor, or allow them to have default values. The C# team chose the latter strategy.