[英]Why does my switch work when it has single quotes?
So disclaimer, I am pretty new to C# and trying to learn the finer intricacies. 所以免责声明,我对C#很新,并试图学习更精细的复杂性。 I have a classwork assignment that I coded and it works, but I'm not sure why it works, and want to understand it. 我有一个我编写的课堂作业并且它有效,但我不确定它为什么有用,并且想要理解它。
Here is the code, Its not the full code, i just cut out the relevant parts: 这是代码,它不是完整的代码,我只是剪切相关的部分:
int studentType = 0;
switch (studentType)
{
case 1:
studentType = '1';
WriteLine("What is your GPA?");
gpa = Convert.ToDouble(ReadLine());
break;
case 2:
studentType = '2';
WriteLine("What is the title of your thesis?");
thesis = ReadLine();
break;
case 3:
studentType = '3';
WriteLine("What is the title of your dissertation?");
dissertation = ReadLine();
break;
case 4:
break;
default:
WriteLine("Invalid option input.");
break;
}//Switch for student Type
As noted, the case command works perfectly fine like this. 如上所述,case命令完全正常。 What I accidently did was initially put case 'x': and that ended up not working, so i deleted all the single quotes. 我意外做的最初是把案例'x':最终没有工作,所以我删除了所有的单引号。
Here is the 2nd part, and why I am confused: 这是第二部分,为什么我感到困惑:
switch (studentType)
{
case '1':
case '4':
WriteLine($"GPA: {gpa:f2}");
break;
case '3':
WriteLine($"Dissertation title: {dissertation}");
break;
case '2':
WriteLine($"Thesis title: {thesis}");
break;
}//end of studentType switch
So originally I tried writing the case without the single quotes, but every time I ran 1, GPA never populated, so I tried to put in the single quotes, and it works, but I'm not sure why. 所以最初我尝试在没有单引号的情况下编写案例,但每次运行1时,GPA都没有填充,所以我尝试输入单引号,它可以工作,但我不知道为什么。
Since studentType is an integer, it would make sense for the first switch to be without single quotes, but how is the switch requiring single quotes? 由于studentType是一个整数,所以第一个开关没有单引号是有意义的,但是这个开关如何需要单引号?
I guess I can submit it as is as long as it works correctly, but I mainly want to understand whats going on. 我想我可以按原样提交,只要它正常工作,但我主要想了解最新情况。
Thanks for the help! 谢谢您的帮助!
There's an implicit conversion from char
to int
, and a constant char
expression can be used as a constant int
expression, which is what you've got. 有一个从char
到int
的隐式转换,并且一个常量char
表达式可以用作常量int
表达式,这就是你所拥有的。 The value of the int
is the UTF-16 code unit associated with the char
. int
的值是与char
关联的UTF-16代码单元。
Here's another example of that: 这是另一个例子:
const int X = 'x';
That's also why your assignment statements worked: 这也是你的任务陈述有效的原因:
studentType = '1';
So this: 所以这:
int value = ...;
switch (value)
{
case '1':
// ...
break;
}
is equivalent to: 相当于:
int value = ...;
switch (value)
{
case 49:
// ...
break;
}
... because 49 is the UTF-16 code point associated with the character '1'. ...因为49是与字符“1”关联的UTF-16代码点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.