根据Visual Studio 2015,第一个case
语句中的第一行代码无法访问,但我不明白为什么。同一case
语句中的第二行代码未标记为无法访问,default
语句中的所有代码均可访问。 VS只是愚蠢还是我错过了什么?
private static void LogToITSupport(string ErrorType)
{
var Email = new MailMessage();
Email.To.Add("");
Email.From = new MailAddress("");
switch ("ErrorType")
{
case "Database Connection":
Email.Subject = "JobSight Error, unable to connect to database.";
Email.Body = "JobSight is unable to connect to the JobSight database, this could indicate the databse is dow nor there is a server problem. Please investigate.";
break;
default:
Email.Subject = "JobSight has encountered an unknown error.";
Email.Body = "JobSight has encountered an unknown error and thinks that IT should fix it. Good Luck.";
break;
}
var Client = new SmtpClient("");
Client.Send(Email);
}
答案 0 :(得分:4)
字符串文字"ErrorType"
永远不能等于"Database Connection"
,所以编译器只是告诉你。
您可能希望改为使用ErrorType
变量:
switch (ErrorType)
{
case "Database Connection":
Email.Subject = "JobSight Error, unable to connect to database.";
Email.Body = "JobSight is unable to connect to the JobSight database, this could indicate the databse is dow nor there is a server problem. Please investigate.";
break;
default:
Email.Subject = "JobSight has encountered an unknown error.";
Email.Body = "JobSight has encountered an unknown error and thinks that IT should fix it. Good Luck.";
break;
}
现在,如果ErrorType
变量等于"Database Connection"
,则将执行第一个语句,否则为默认语句。此评估将在运行时完成,具体取决于字符串变量的值。
答案 1 :(得分:4)
回答你的实际问题。您正在打开文字字符串" ErrorType"你的选择是"数据库连接"或其他任何事情。
由于编译器正在查看文字字符串,因此它知道DataBase Connection永远不会出现这种情况,因此无法访问。
例如,如果您将交换机更改为" DataBase Connection"你会注意到第一行是正常的但是你会在默认情况下收到该错误,因为编译器知道数据库连接是唯一可以达到的。
使用实际的变量开关(ErrorType),编译器不知道将传入的内容,因此大小写和默认值都可以访问。
正如其他人所指出的,删除引号是因为您想要打开变量ErrorType所持有的字符串。