[英]Why does my switch work when it has single quotes?
所以免責聲明,我對C#很新,並試圖學習更精細的復雜性。 我有一個我編寫的課堂作業並且它有效,但我不確定它為什么有用,並且想要理解它。
這是代碼,它不是完整的代碼,我只是剪切相關的部分:
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
如上所述,case命令完全正常。 我意外做的最初是把案例'x':最終沒有工作,所以我刪除了所有的單引號。
這是第二部分,為什么我感到困惑:
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
所以最初我嘗試在沒有單引號的情況下編寫案例,但每次運行1時,GPA都沒有填充,所以我嘗試輸入單引號,它可以工作,但我不知道為什么。
由於studentType是一個整數,所以第一個開關沒有單引號是有意義的,但是這個開關如何需要單引號?
我想我可以按原樣提交,只要它正常工作,但我主要想了解最新情況。
謝謝您的幫助!
有一個從char
到int
的隱式轉換,並且一個常量char
表達式可以用作常量int
表達式,這就是你所擁有的。 int
的值是與char
關聯的UTF-16代碼單元。
這是另一個例子:
const int X = 'x';
這也是你的任務陳述有效的原因:
studentType = '1';
所以這:
int value = ...;
switch (value)
{
case '1':
// ...
break;
}
相當於:
int value = ...;
switch (value)
{
case 49:
// ...
break;
}
...因為49是與字符“1”關聯的UTF-16代碼點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.