Jon Skeet,如果你在听,你可能会感兴趣,因为它与你的代码难题有关... http://codeblog.jonskeet.uk/2014/01/14/a-tale-of-two-puzzles/
代码
public class Test
{
public static void Main()
{
bool? x = (true) ? null : default(bool?);
bool? y = (true) ? x is bool? : default(bool?);
Console.WriteLine(x);
Console.WriteLine(y);
Console.Read();
}
}
输出
False
令我困惑的是,我期望看到这个......
True
bool? y = (true) ? x is bool? : default(bool?);
因为 : default(bool?)
永远不会被命中,为什么 x 是 bool?
返回 false
,当它是 bool ?
?
最佳答案
第一个语句显然将 x
的值设置为 null
。第二条语句检查 x
的值是否"is"bool?
。
is
运算符不关心变量的声明 类型。它查看正在评估的对象的实际 类型。由于 x
设置为 null
,因此传递给 is
运算符的 value 为 null
,意味着没有对象被引用,因此 is bool?
返回 false
。
来自 MSDN :
An
is
expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
关于C# 代码拼图返回令人费解的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36205953/