C# 代码拼图返回令人费解的结果

标签 c#

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 运算符的 valuenull,意味着没有对象被引用,因此 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/

相关文章:

c# - 更改按钮图像

c# - 当非键列中的一个值包含 null 时,如何在 GroupBy 语句中返回 null?

c# - 如何在 asp.net c# mvc 中为现有软件创建 SaaS 应用程序

c# - unity rigidbody2d倾斜问题

c# - 我可以在不知道 dll 文件名的情况下加载程序集吗,我只知道命名空间名称

c# - 表达式树转换到 ICollection<T> 并添加

c# - .NET 等同于 GetLastInputInfo?

c# - Xamarin .net 标准对 APK 大小的影响

C# Serilog 仅在错误后收到电子邮件

c# - EPPlus 设置默认工作表