代码之家  ›  专栏  ›  技术社区  ›  Muflix

如何在VisualStudio中检测IF条件中的赋值而不是相等运算符?

  •  1
  • Muflix  · 技术社区  · 5 年前

    var isFoo = true;
    var bar = 1;
    if (isFoo = false && bar > 0) // Compiler is not warning about assignment instead of equality
    {
    // ...
    }
    

    3 回复  |  直到 5 年前
        1
  •  1
  •   TheNightdrivingAvenger    5 年前

    大多数C/C++编译器在特定的警告级别上提供这样的警告。不幸的是,我无法为VisualStudio的C#/.NET编译器找到相同的设置。

    code analyzers 这可能会提供额外的灵活性,强制您需要的代码规则。

    我自己还没有用过,但我相信这是正确的方向。

        2
  •  1
  •   eglease Darrin    5 年前

    ReSharper . 它将警告您表达式始终为true/false。

    enter image description here

    您可能还会收到编译器警告 CS0162: Code is unreachable

        3
  •  -1
  •   Panagiotis Kanavos    5 年前

    编译器没有错误地进行检测。赋值是返回赋值的表达式。 isFoo = false (false && bar >0) 这总是错误的。 那是 代码分析器可以检测到的东西:表达式总是false。

    StreamReader docs 该示例使用此选项一次读取一行文本:

    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
       string line;
       // Read and display lines from the file until the end of
       // the file is reached.
       while ((line = sr.ReadLine()) != null)
       {
           Console.WriteLine(line);
       }
    }