c#切换问题 [英] c# switch problem

查看:16
本文介绍了c#切换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,对以下代码有疑问:

I'm new to programming and having a problem with the following code:

    private string alphaCoords(Int32 x)
    {
        char alphaChar;

        switch (x)
        {
            case 0: alphaChar = 'A'; break;
            case 1: alphaChar = 'B'; break;
            case 2: alphaChar = 'C'; break;
            case 3: alphaChar = 'D'; break;
            case 4: alphaChar = 'E'; break;
            case 5: alphaChar = 'F'; break;
            case 6: alphaChar = 'G'; break;
            case 7: alphaChar = 'H'; break;
            case 8: alphaChar = 'I'; break;
            case 9: alphaChar = 'J'; break;
        }

        return alphaChar.ToString();
    }

编译器说:使用未分配的局部变量'alphaChar'

The compiler says: Use of unassigned local variable 'alphaChar'

但我在我的 switch 块中分配它.

But I'm assigning it in my switch block.

我确定这是我的错,因为我对编程不够了解.

I'm sure this is my fault as I dont know enough about programming.

请指教.

谢谢.

推荐答案

如果 x 是 0-9,你正在分配它.如果 x 是 123,你希望它做什么?虽然可能知道只会传入 0 到 9 之间的值,但编译器不会 - 所以 需要考虑否则会发生什么.

You're assigning it if x is 0-9. What would you expect it to do if x were 123 though? While you may know that only values between 0 and 9 will be passed in, the compiler doesn't - so it needs to consider what would happen otherwise.

避免这种情况的一种方法是在 switch 语句中使用 default 大小写,如果值不在预期范围内,您可以使用它来引发异常:

One way to avoid this is to have a default case in your switch statement, which you can use to throw an exception if the value isn't in the expected range:

switch (x)
{
    case 0: alphaChar = 'A'; break;
    case 1: alphaChar = 'B'; break;
    case 2: alphaChar = 'C'; break;
    case 3: alphaChar = 'D'; break;
    case 4: alphaChar = 'E'; break;
    case 5: alphaChar = 'F'; break;
    case 6: alphaChar = 'G'; break;
    case 7: alphaChar = 'H'; break;
    case 8: alphaChar = 'I'; break;
    case 9: alphaChar = 'J'; break;
    default: throw new ArgumentOutOfRangeException();
}

这里有一个稍微简单的替代方案,它完全删除了你的 switch 语句:

Here's a slightly simpler alternative though, which removes your switch statement completely:

if (x < 0 || x > 9)
{
    throw new ArgumentOutOfRangeException();
}
char alphaChar = (char)('A' + x);

请注意,您在使用这样的算术时确实需要小心.在 Java 和 C# 中,底层表示保证是 Unicode,这让生活变得更加轻松.我相信这样的事情(和十六进制解析/格式化)很好,但是当你冒险进入更奇特的场景时,它会失败.话又说回来,很多代码简化技术都是如此……如果应用不当,最终会变得一团糟.

Note that you do need to exercise care when using arithmetic like this. In Java and C# the underlying representation is guaranteed to be Unicode, which makes life a lot easier. I believe it's fine for things like this (and hex parsing/formatting) but when you venture into more exotic scenarios it would fail. Then again, that's true for a lot of code simplification techniques... if they're applied inappropriately, you end up with a mess.

这篇关于c#切换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆