简体   繁体   English

为什么Resharper认为私有只读变量可以为null?

[英]Why does resharper think a private readonly variable can be null?

In the following code, Resharper 8 tells me that _myClasses has a "Possible 'System.NullReferenceException'". 在下面的代码中,Resharper 8告诉我_myClasses具有“可能的'System.NullReferenceException'”。 Is this a bug in Resharper or is there something I am missing about how this code will work? 这是Resharper中的错误,还是我缺少有关此代码如何工作的信息? My understanding is that the readonly modifier makes it so I can only set _myClasses once and the one thing I am setting it to is an instance of something. 我的理解是readonly修饰符可以实现,因此我只能设置_myClasses一次,而我将其设置为的一件事是某事物的实例。 What scenario could this be null? 在什么情况下可以为空?

private readonly IList<MyClass> _myClasses = new List<MyClass>();

void Foo()
{
    _myClasses.Clear(); // Possible 'System.NullReferenceException'
}

readonly means "can't change after constructor is completed". readonly表示“构造函数完成无法更改”。 So any constructor can change its value to null (now or future written constructor). 因此,任何构造函数都可以将其值更改为null(现在或将来编写的构造函数)。

...assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. ...对声明所引入字段的分配只能作为声明的一部分或在同一类的构造函数中进行。

Sample: 样品:

class Foo
{
  private readonly string myClasses = "test";

  public Foo(int value) {  }    
  public Foo(string text) {  myClasses = text;}    
  public Foo() 
  {
     myClasses = null;
     Bar();
  }

  void Bar()
  {
    if (myClasses == null)
    {
     Console.WriteLine("Null???");
    }
  }
}

In sample above Foo() constructor will set myClasses to null and case exception if one relies on this value not be null. 在上面的示例中, Foo()构造函数将myClasses设置为null ,如果一个依赖于此值的值不为null,则将大小写异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM