if(string s; s = Console.ReadLine(); s == "ja" || "Ja")
A screenshot of all the errors i got from that single line I dont understand a single of them 有人能解释我的if语句似乎不被接受
if(string s; s = Console.ReadLine(); s == "ja" || "Ja")
A screenshot of all the errors i got from that single line I dont understand a single of them 有人能解释我的if语句似乎不被接受
你不能声明if
语句里面的变量,这也是无效:s == "ja" || "Ja"
,你需要这样的每个条件分开:
string s = Console.ReadLine();
if(s == "ja" || s == "Ja")
或者,你可以使用:
if(s.ToLower() == "ja")
这不是一个有效的C#语法。在if
语句中,应该有一个评估结果为布尔值。不能在里面声明新的变量,s == "ja" || "Ja"
也没有任何意义。
string s;
s = Console.ReadLine();
if(s == "ja" || s== "Ja")
{
}
?
C#不允许这样的事情。尝试如下:
string s = Console.ReadLine() ;
bool isEndOfFile = s == null ; // Console.ReadLine() returns null at end-of-file
if (isEndOfFile) throw new Exception("That was unexpected!") ;
bool isYes = !isEndOfFile && s.Trim().Equals("Ja" , StringComparison.CurrentCultureIgnoreCase) ;
if (isYes)
{
HandleYesInput() ;
}
一般来说,保持简单。 有意编程将帮助您:以声明方式工作,使用小型离散方法和局部变量作为您正在测试的每个条件的标志来表达您的意图,而不是试图在一个复杂表达式中做所有事情。你可以做这样的事情:
string s = null ;
if ((s=Console.ReadLine()) && s != null && s.Trim().Equals("Ja",StringComparison.CurrentCulture.IgnoreCase))
{
...
}
您在可读性,可追踪性和可调试为代价换取一点简洁。当您的代码无法按预期工作时,您认为哪个版本更易于理解或诊断和修复?如果被分配解决问题任务的人不理解代码或者试图完成的任务并且必须快速加速,那么这会变成三倍。
这个人可能是你,看着你5年前写的代码。
移动'string s; s = Console.ReadLine();'if之外。 –
C#具有定义在“if”内可以出现哪些操作的语法规则,还可以键入用于定义哪些对象可以与某些操作符一起使用的规则。你忽略了所有的规则。 –
[study!](http://msdn.microsoft.com/en-us/library/5011f09h.aspx) – RadioSpace