我正在完善对数组以及if / else if / else语句的理解。我想看看是否可以将if / else if / else语句转换为Switch / Case。最好的方法是什么?我听说Switch / Case在处理更多选择时效率更高。我应该留在if / else吗?还是有办法将我的选择转换成Switch Case?这是我为他们和代码中的示例。
{
int [] acct = new int [3];
acct[0] = 8675309;
acct[1] = 8675310;
acct[2] = 8675311;
Console.WriteLine("Enter your account number");
int myacct = int.Parse(Console.ReadLine());
//int myacct = Convert.ToInt32(Console.ReadLine());<--This works too
if (myacct == acct[0])
{
Console.WriteLine("What is your name?");
}
else if (myacct == acct[1])
{
Console.WriteLine("What is your name?");
}
else if (myacct == acct[2])
{
Console.WriteLine("What is your name?");
}
else
{
Console.WriteLine("Sorry you don't have access");
}
string name = Console.ReadLine();
string[] names = new string[3] { "Jenny", "Roberto", "Sally" };
/* This shows them how to tighten the code up compaired to the technique we used above
names[0] = "Jenny";
names[1] = "Roberto";
names[2] = "Sally";
*/
//I'd like to make the following code into a Switch and Case type statement instead of using else if.
/*
if (myacct == acct [0] && name == "Jenny")
{
Console.WriteLine("Welcome "+names[0] + "!");
}
else if (myacct == acct[1] && name == "Roberto")
{
Console.WriteLine("Welcome Roberto" + names[1] + "!");
}
else if (myacct == acct[2] && name == "Sally")
{
Console.WriteLine("Welcome Sally" + names[2] + "!");
}
else
{
Console.WriteLine("Account number and Names do not match");
}
*/
}
}
为您提供使用开关的想法:
switch (myacct)
{
case acct[1]:
break;
case acct[2]:
break;
case acct[3]:
break;
default: // your "else"
break;
}
您无法切换多个变量,因此无法组合myacct
和name
。
我这样看:
switch(value)
声明编码器打算基于value
]做出分支决策>if
-else if
可以有任意条件if
而不是else if
,这可能导致错误或对原始编码者意图的误解。高达C#6.0 switch
的case
could only operate具有恒定值,这意味着如果if
-else if
链更灵活,则可能很难将其直接转换为switch
]在C#6.0及更低版本中。
从C#7.0开始,引入了更灵活的pattern matching,使得可以使用非恒定模式。
在C#8.0中,还存在switch expressions,property and tuple patterns,在某些情况下,它们可以使代码更具可读性和简洁性。