【问题标题】:Switch on Nullable Boolean : case goes to null when value is true打开 Nullable Boolean :当值为 true 时,case 变为 null
【发布时间】:2015-12-19 15:08:54
【问题描述】:

我意识到处理可空类型的正确方法是使用 HasValue 属性。但是我想知道为什么下面的 switch 语句会在 null 情况下而不是默认情况下中断。使用 VS2015 C#4.0。另一台使用 VS2010 C#4.0 的电脑没有这个问题。

 private void Testing()
    {
        bool? boolValue = true;

        switch (boolValue)
        {
            case null: 
                break; //even though value is true, code runs here

            default:
                break;
        }
    }

编辑:只要指定了case Nulldefault,任何Nullable 的行为都会被观察到。

【问题讨论】:

  • 我在 VS2013 上没有这种行为
  • 我猜你的符号已经过时并且它没有运行你认为它正在运行的东西,或者编译器正在做一些奇怪的优化事情并组合两个相等的块。也许在那里添加一些实际的代码,看看它做了什么..
  • 我在 2010 年没有这种行为。
  • 您是在查看调试器告诉您的内容,还是在这两种情况下也看到了实际不同的代码?
  • 你检查过 IL 吗? (与 ildasm?)

标签: c# visual-studio-2015


【解决方案1】:

这将是一个非常简短的答案:您只需点击 Roslyn bug #4701,两周前报告。

里程碑设置为 1.1,因此现在您必须使用单独的 if 子句解决此问题,同时等待下一次编译器更新。

【讨论】:

    【解决方案2】:

    这不是答案,我只是分享VS2013和VS2015生成的IL代码。

    原始C#代码:

    public void Testing()
    {
        bool? boolValue = true;
    
        switch (boolValue)
        {
    
            case null:
    
                Console.WriteLine("null");
    
                break; 
    
            default:
                Console.WriteLine("default");
    
                break;
        }
    }
    

    VS2013 IL(反编译):

    public void Testing()
    {
        bool? boolValue = new bool?(true);
        bool valueOrDefault = boolValue.GetValueOrDefault();
        if (boolValue.HasValue)
        {
            Console.WriteLine("default");
        }
        else
        {
            Console.WriteLine("null");
        }
    }
    

    VS2015 IL(反编译):

    public void Testing()
    {
        bool? flag = new bool?(true);
        bool? flag2 = flag;
        bool? flag3 = flag2;
        if (flag3.HasValue)
        {
            bool valueOrDefault = flag3.GetValueOrDefault();
        }
        Console.WriteLine("null");
    }
    

    【讨论】:

    • 对我来说只有一个变量nullable2。不是标志1,2,3。但似乎默认部分根本无法编译。问题在于所有可为空的类型
    • 也许它也取决于反编译器。我正在使用 ILSpy
    • 我有版本 14.0.23107.0 D14REL,你有什么版本的@vendettamit?
    猜你喜欢
    • 2012-04-02
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多