【问题标题】:Nullable Long switch statement not producing expected output in VS2015Nullable Long switch 语句在 VS2015 中没有产生预期的输出
【发布时间】:2016-01-22 06:14:08
【问题描述】:

在 VS2015 Update 1 中使用可为空的长 switch 语句时,我看到了一些奇怪的行为,而在其他 Visual Studio 版本中没有看到它按预期运行。

class Program
{
    static void Main(string[] args)
    {
        NullableTest(-1);
        NullableTest(0);
        NullableTest(1);
        NullableTest(2);
        NullableTest(null);
    }

    public static void NullableTest(long? input)
    {
        string switch1;
        switch (input)
        {
            case 0:
                switch1 = "0";
                break;
            case 1:
                switch1 = "1";
                break;
            default:
                switch1 = "d";
                break;
        }

        string switch2;
        switch (input)
        {
            case -1:
                switch2 = "-1";
                break;
            case 0:
                switch2 = "0";
                break;
            case 1:
                switch2 = "1";
                break;
            default:
                switch2 = "d";
                break;
        }

        string ifElse;
        if (input == 0)
        {
            ifElse = "0";
        }
        else if (input == 1)
        {
            ifElse = "1";
        }
        else
        {
            ifElse = "d";
        }
        Console.WriteLine("Input = {0}, Switch 1 output = {1}, Switch 2 output = {2},  If Else = {3}", input, switch1, switch2,  ifElse);
    }

此示例代码产生以下输出(对齐以便于阅读):

Input = -1, Switch 1 output = d, Switch 2 output = d,  If Else = d
Input = 0,  Switch 1 output = 0, Switch 2 output = d,  If Else = 0
Input = 1,  Switch 1 output = d, Switch 2 output = d,  If Else = 1
Input = 2,  Switch 1 output = d, Switch 2 output = d,  If Else = d
Input = ,   Switch 1 output = d, Switch 2 output = d,  If Else = d

我只在 Nullable 类型中观察到这种行为。不可为空的类型按预期工作。

请注意,这不是this question 中的行为相同,并且不是由 VS2015 Update 1 中修复的this 编译器错误引起的。我已经验证了这两个示例都运行正确。

【问题讨论】:

    标签: c# visual-studio-2015 switch-statement nullable


    【解决方案1】:

    看起来这是由this bug 引起的,并已用this pull request 修复。

    我已经尝试了 Roslyn 的最新版本,问题中的示例代码现在可以按预期工作。

    Here 是已更正此问题的 MSBuild Tools 2015 的更新版本。

    【讨论】:

      【解决方案2】:

      这是一个错误。我相信它一定是同一个bug 的遗留物。您最好用 If 替换您的代码以避免任何意外行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多