简体   繁体   English

变量已分配但从未使用其值 (C#)

[英]Variable is assigned but its value is never used (C#)

In Visual Studio I used the following code:在 Visual Studio 中,我使用了以下代码:

 private bool answer = true;
    Private Buttonclick()
   {
      if()
       {
        answer =false
        }
   }

Compiler gives me a warning that says "answer is assigned but its value is never used".编译器给我一个警告,说“已分配答案,但从未使用过它的值”。 How do I fix this?我该如何解决?

It means you have given answer a value, but not referenced it elsewhere.这意味着你已经给了answer一个值,但没有在其他地方引用它。 Meaning you are not using answer elsewhere in your program.这意味着您没有在程序的其他地方使用答案。

You fix it by referencing answer from another part of your program.您可以通过引用程序另一部分的答案来修复它。

The reason the warning pops up is not because the variable is never assigned, but because it is in fact never used for any sort of comparison in the rest of the code.弹出警告的原因不是因为变量从未被赋值,而是因为它实际上从未用于其余代码中的任何类型的比较。

Please go through this reference: http://weblog.west-wind.com/posts/2009/Feb/28/Variable-is-assigned-but-its-Value-is-never-used-Warning请阅读此参考: http : //weblog.west-wind.com/posts/2009/Feb/28/Variable-is-assigned-but-its-Value-is-never-used-Warning

If you want to disable warnings, the error list contains a button that can stop them being shown in the list.如果您想禁用警告,错误列表包含一个按钮,可以阻止它们显示在列表中。

在此处输入图片说明

Additionally, a warning is just a warning.此外,警告只是警告。 They won't stop your program from compiling, or even running.它们不会阻止您的程序编译甚至运行。 They may, however, declare in advance runtime errors and the like, so don't ignore them completely.但是,它们可能会提前声明运行时错误等,因此不要完全忽略它们。

In addition to the answers above, for more deep understanding of the this warning:除了上面的答案,为了更深入地理解这个警告:

This warning will not always pop-up (if you not use assigned variable).此警告不会总是弹出(如果您不使用分配的变量)。 Assigning a non-constant expression or method result will NOT generate the warning.分配非常量表达式或方法结果不会生成警告。 It is done intentionally, since such an unassigned variables can be used in debugging.这是有意完成的,因为这样的未分配变量可用于调试。

For example:例如:

 var answer = SomeObject.SomePropery; //will not generate CS0219

There are excellent explanation in Microsoft.Docs: https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0219 Microsoft.Docs 中有很好的解释: https : //docs.microsoft.com/en-us/dotnet/csharp/misc/cs0219

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

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