c# - 为什么VS认为这个说法总是正确的?

标签 c# visual-studio if-statement

我有这个 if 语句 -

if (!((main.property == 1)||(main.property == 2)))
{
   ...
}

main.property 是一个字节,可以是 0、1、2 或 98。

Visual Studios 说这个陈述总是正确的,但我不明白为什么?

如果属性是 1 或 2,这不应该是 false。

提前谢谢你。

编辑:添加代码

文件1.cs

private void Upload(DataSet ds)
{
    Main main = CreateMain(ds); //This is tested and works correctly
    if(ValidateDate(main))
    {
        ...
    }
}

文件2.cs

internal static bool ValidateData(Main main, ...)
{
    if (!((main.property == 1)||(main.property == 2)))
    {
        ...
    }
}

编辑:添加代码

如果我这样做,错误就会消失 -

internal static bool ValidateData(Main main, ...)
{
     main.property = 0; //Or = any number
     if (!((main.property == 1)||(main.property == 2)))
     {
          ...
     }
}

我猜 VS 认为它没有初始化,但我 100% 肯定它是。

最佳答案

我写了这个小程序来检查它:

    class Program
{
    static void Main(string[] args)
    {
        test(0);
        test(1);
        test(2);
        test(3);
        Console.ReadLine();
    }

    private static void test(int p)
    {
        bool b1 = (!((p == 1) || (p == 2)));
        bool b2 = (p != 1 && p != 2);
        Console.Out.WriteLine("{0} {1} {2}", b1, b2, b1 == b2);
    }
}

Constantin 的抄写似乎是正确的,但是这两种表述都不是永远正确或永远错误的。

关于c# - 为什么VS认为这个说法总是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3501079/

相关文章:

c# - Entity Framework 6 异常 : "The context cannot be used while the model is being created"

c++ - 创建一个可以是多种类型的 C++ 数组

java - 在java中将多个if语句组合为一个输入

c++ - if语句跳转

c# 遍历数据表,更改数据

c# - 停止/启动后 URI 的注册已经存在

c# - 将文件拖放到程序中

visual-studio - 如何确保 nuget 程序集是按包添加的,而不仅仅是对 DLL 文件的引用?

asp.net - 如何避免从Visual Studio以 Debug模式发布ASP.NET应用程序?

c++ - VS2017 中未生成警告