时间:2019-03-17 标签:c#switch

发布于 2024-08-16 20:57:22 字数 763 浏览 6 评论 0原文

我是编程新手,并且对以下代码有问题:

    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”

但我将其分配在我的 switch 块中。

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

请指教。

谢谢。

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();
    }

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

But I'm assigning it in my switch block.

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

Please advise.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

弥繁 2024-08-23 20:57:22

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

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

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 语句:

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

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

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.

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();
}

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);

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.

时光与爱终年不遇 2024-08-23 20:57:22

编译器会抱怨,因为 alphaChar可能 未定义 - 如果它不是 switch 中的值之一,那么它就不会被定义。您可以执行以下操作之一:

  • 设置 char 的初始值,如果没有一个切换条件为 true,则将执行该初始值。
  • 在 switch 语句中添加“default”子句。

The compiler is complaining because alphaChar is possibly undefined -- if it is not one of the values in your switch then it will not have been defined. You can do one of the following things:

  • Set an initial value of char which will be carried through if none of the switch conditions is true.
  • Add a "default" clause to your switch statement.
爱殇璃 2024-08-23 20:57:22

在首次使用局部变量之前,必须明确对其进行赋值(根据 C# 规范规则)。在这种特殊情况下, switch 构造不能保证 alphaChar 将被明确分配,因此会出现编译器错误。您可以为 alphaChar 提供初始值,因此它肯定会被分配。

Before its first use local variable must be definitely assigned (according to C# specification rules). In this particular case switch construct doesn't guarantee that alphaChar will be definitely assigned thus compiler error. You can provide initial value to alphaChar and thus it will be definitely assigned.

兮子 2024-08-23 20:57:22

您需要在 switch 语句中添加默认值。

编译器指出在某些情况下不会为变量赋值。因此,添加

default:
  alphaChar = 'x'
break;

将告诉编译器“所以,如果我错过了某些场景,请将值设为此值”,

或者在不想分配默认值的情况下:

  default: throw new Exception();

这不一定更好,而是另一种实现方式:

 private string alphaCoords(Int32 x)
    {
      if(x >= 0 && x =< 9)
           return ((char)(x + 65)).ToString();
      else
        throw new ArgumentException();
    }

You need to add a default to your switch statement.

The compiler is stating that there are some cases which will not assign a value to the variable. So adding

default:
  alphaChar = 'x'
break;

will tell the compiler "so in case I miss some scenario, make the value this"

or in the case of not wanting to assign a default:

  default: throw new Exception();

This is not necessarily better but another way of doing it:

 private string alphaCoords(Int32 x)
    {
      if(x >= 0 && x =< 9)
           return ((char)(x + 65)).ToString();
      else
        throw new ArgumentException();
    }
凉月流沐 2024-08-23 20:57:22

您根据某些条件为变量 alphaChar 赋值。想象一个场景,变量x包含0到9以外的值。假设它包含10。那么x将不满足任何case条件,因此alphaChar 将不会被分配任何值,因此它将完全未初始化。因此,当您将 alphaChar 转换为字符串时,它会将一些垃圾值转换为字符串并将其返回给调用方法。这就是您收到该消息的原因。

如果你想得到一个简单的解决方案,那么在下面添加以下代码

case 9: alphaChar = 'J'; 
        break; 

-

default: return null;

并在调用方法中检查这个 alphaCoords 函数是否返回 null,就像这样 -

if(alphaCooord(10) == null)
{
    // x contains value other than 0 to 9
}
else
{
    // x contains value between 0 to 9, so the returned value will be the string
    // representation of the corresponding character
}

这样你的代码就不会被太复杂,或者您不需要抛出或处理任何异常或类似的东西。

希望有帮助:)。

You are assigning value to the variable alphaChar based on some condition. Imagine a scenario where the variable x contains value other than 0 to 9. Suppose it contains 10. Then none of the case conditions will be satisfied by x, so alphaChar will not be assigned any value, as a result it will be totally uninitialized. So when you are converting alphaChar to string, it is converting some garbage value to string and returning it to the calling method. This is the reason why you are getting that message.

If you want to get a simple solution, then add the following code below

case 9: alphaChar = 'J'; 
        break; 

-

default: return null;

and check in the calling methods whether this alphaCoords function returns null or not, like this -

if(alphaCooord(10) == null)
{
    // x contains value other than 0 to 9
}
else
{
    // x contains value between 0 to 9, so the returned value will be the string
    // representation of the corresponding character
}

In this way your code won't be too complex, or you won't need to throw or handle any exceptions or something like that.

Hope that helps :).

带上头具痛哭 2024-08-23 20:57:22

编译器无法知道变量 x 只能包含最多 9 的数字(这是您在 switch 中检查的内容)。由于您的开关中缺少 default 大小写,因此 alphaChar 可能会保持未分配状态。您可以在switch 之前添加一个default 情况或为变量分配一个值。

The compiler has no way of knowing that the variable x can only contain numbers up to 9 (which is what you check in your switch). Since the default case is missing from your switch it can happen that alphaChar remains unassigned. You can either add a default case or assign the variable a value before the switch.

吃颗糖壮壮胆 2024-08-23 20:57:22

为您的开关添加默认值,因为如果 x 为 10,则 alphaChar 将永远不会被分配。

Add a default to your switch, because if x is 10, alphaChar will never be assigned.

謸气贵蔟 2024-08-23 20:57:22

声明变量 char alphaChar 后,您应该为其“分配”一个值(将其设置为等于某个值),即使您希望它在 switch 语句中获得一个值。

您可以将其指定为“A”或“0”或几乎任何内容。

您可以在这样的声明中执行此操作

char alphaChar = 'A';

或者您可以单独执行此操作

char alphaChar;    
alphaChar = 'A';

After you declare the variable char alphaChar, you should "assign" a value to it (set it to be equal to something), even though you expect it to get a value in the switch statement.

You could assign it 'A' or '0' or pretty much anything.

You can do that in the declaration like this

char alphaChar = 'A';

Or you can do it separately

char alphaChar;    
alphaChar = 'A';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文