C#开关问题 [英] c# switch problem
问题描述
我是新来编程,并具有下列代码的问题:
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'
但我在我的开关模块分配它。
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语句,你可以用它来抛出,如果一个异常默认
情况值不在预期范围:
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屋!