我有这个 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/