【发布时间】:2015-08-14 11:43:41
【问题描述】:
以下this very interesting issue 源自this 问题-
我想退一步请(去掉动态环境):
看这段代码:(a variant of this one)
void Main()
{
int a;
int b = 100;
Console.WriteLine(X.M(1, out a));
}
public class X
{
public int H=0;
public static X M(int x, out int y)
{
Console.WriteLine("x = "+x);
y = x;
return new X(x);
}
public X(){}
public X(int h)
{
H=h;
}
public static bool operator false(X x) {Console.WriteLine("in false operator for "+ x.H); return true; }
public static bool operator true(X x) {Console.WriteLine("in true operator for "+ x.H); return true; }
public static X operator &(X a, X b) {Console.WriteLine("in & operator for "+ a.H+","+b.H); return new X(); }
public static implicit operator bool (X x) {Console.WriteLine("in bool operator for "+ x.H);return true; }
}
结果是:
x = 1
in bool operator for 1
True
这是明白的:
-
x = 1来自方法本身(使用Console.Writeline) -
in bool operator for 1是从X到Bool的隐式运算符 (所以 -Console.WriteLine将整个表达式视为Console.Writeline(bool)) - 最后一个“True”来自
operator bool (X x)中的“return true”
好的 - 所以让我们改变
Console.WriteLine(X.M(1, out a));
到
Console.WriteLine(X.M(1, out a) && X.M(2, out b));
现在 - 结果是:
x = 1
in false operator for 1
in bool operator for 1
True
2 个问题:
为什么这个
in false operator for 1会执行?我看不出有任何理由让false出现在这里。我可以理解为什么
X.M(1, out a) && X.M(2, out b)中的右侧部分只有在左侧部分是false时才会执行 - 但我还是不明白左侧部分怎么可能是假的。它确实返回true(根据我的第一个代码)
注意
我已经多次阅读帖子中的答案:
乔恩说:
第二个 && 是两个布尔表达式之间的普通 && - 因为 Nop 返回 bool,并且没有 &(X, bool) 运算符...但是有一个 从 X 到 bool 的转换。
所以它更像是:
bool first = X.M(1, out a) && X.M(2, out b);
if (first && Nop(a, b))尽管只有 && 的第一个操作数是 评估...所以 b 真的没有被分配。
我还是不明白:“第一个是 true(????) 尽管只计算了 && 的第一个操作数”
【问题讨论】:
-
如果
false()操作符返回true,则表示该操作返回false("is x false? yes it is (return true;)")!这不是operator bool()。 -
调用
false()运算符来短路&&... 他们本可以调用true()运算符,但例如msdn 中&&的定义: 除了如果 x 为假,不计算 y -
参见stackoverflow.com/a/5203515/613130:&& 被定义为短路操作符; 如果第一个操作数计算为假,则要求在此处短路而不计算右侧。
-
@xanatos 是的。但这就是我看不到第一个操作数在哪里获得错误值的问题。
-
因为
&&运算符被翻译成if(not operator false(left expression))然后计算右表达式
标签: c#