今天我在写代码,发现有些东西没有按照我的预期工作。
为什么下面的代码会执行,即使条件本应该被评估为false? alt text http://img215.imageshack.us/img215/3011/agfewrf.gif 我已经尝试过在两个条件周围加上大括号,并交换它们的位置,但EndedUsingApplication仍然被执行。
编辑:
这与||或&&运算符无关。看这里...
为什么下面的代码会执行,即使条件本应该被评估为false? alt text http://img215.imageshack.us/img215/3011/agfewrf.gif 我已经尝试过在两个条件周围加上大括号,并交换它们的位置,但EndedUsingApplication仍然被执行。
编辑:
这与||或&&运算符无关。看这里...
除非我发布罪犯代码,否则没有人能从我的错误中学习,所以这里是代码。
public static bool operator ==(ActiveApplication a, ActiveApplication b)
{
if ((object)a == null || (object)b == null)
return false;
return a.process_name == b.process_name && a.window_title == b.window_title;
}
public static bool operator !=(ActiveApplication a, ActiveApplication b)
{
return a == b ? false : true;
}
以下是可用的代码...
public static bool operator ==(ActiveApplication a, ActiveApplication b)
{
// Casting to object class prevents this comparison operator being executed
// again and causing an infinite loop (which I think .NET detects and stops
// but it would still be a huge hole in the logic.
if ((object)a == null && (object)b == null)
return true;
if ((object)a == null ^ (object)b == null)
return false;
return a.process_name == b.process_name && a.window_title == b.window_title;
}
public static bool operator !=(ActiveApplication a, ActiveApplication b)
{
return a == b ? false : true;
}
问题似乎出现在"!="运算符接收到两个null值时。
==
还是object.ReferenceEquals()
? - John Alexiou