Compile-time detection of accidentally assign a C# property to itself

前端 未结 2 1973
不思量自难忘°
不思量自难忘° 2021-02-06 07:59

Visual Studio C# compiler warns about accidentally assigning a variable to itself, but this warning does not apply to C# properties, only variables. As described in this other q

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 08:33

    Change the way you type the parameters, so the error happens less often.

    Parameter first:

       public Foo(ILogger logger)
       { 
       }
    

    Assignment next: copy/paste the parameter twice

       public Foo(ILogger logger)
       { 
           // this.{paste} = {paste};
           this.logger = logger;
       } 
    

    Lastly, correct the misspelt property:

       public Foo(ILogger logger)
       { 
           this.Logger = logger;
       } 
    

提交回复
热议问题