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

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

在Visual Studio中我使用了以下代码:

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

编译器给我一个警告说 "answer is assigned but its value is never used"。 我该如何解决这个问题?

这意味着您已经给 answer 一个值,但没有在别处引用它。这意味着您没有在程序的其他地方使用 answer 。

您通过引用程序另一部分的答案来修复它。

如果您想禁用警告,错误列表包含一个按钮,可以阻止它们在列表中显示。

此外,警告只是警告。他们不会阻止您的程序编译,甚至 运行。但是,它们可能会提前声明运行时错误等,因此请不要完全忽略它们。

弹出警告的原因不是因为从未分配变量,而是因为它实际上从未在其余代码中用于任何类型的比较。

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

除了上面的回答,更深入的理解这个警告:

这个警告不会总是pop-up(如果你不使用赋值变量)。分配 non-constant 表达式或方法结果不会生成警告。这是有意为之的,因为这样一个未分配的变量可以在调试中使用。

例如:

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

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