Zuz*_*zlx 2 c# if-statement visual-studio-2012
我这里有这段代码.在case ServiceType.Register: 我看来有两个等效语句,一个使用常规if语句,一个使用三元运算符?/:.对于if语句VS报告没有错误.但是这条线:
IsXML == true ? PopulateRegister(ParseType.Xml) : PopulateRegister(ParseType.Str);
VS错误地说:
只有赋值,调用,递增,递减,等待和新对象表达式才能用作语句
任何人都知道为什么常规if语句没有错误,但如果你使用"?/:"(一个班轮)引发错误?Pic也附上了.
switch (this.ServiceType)
{
case SerivceType.Login:
PopulateLogin();
break;
case SerivceType.Register:
if (IsXML == true)
PopulateRegister(ParseType.Xml);
else
PopulateRegister(ParseType.Str);
IsXML == true ? PopulateRegister(ParseType.Xml) : PopulateRegister(ParseType.Str);
break;
case SerivceType.Verify:
PopulateVerify();
break;
}
Run Code Online (Sandbox Code Playgroud)

该?:运营商用于有条件分配,不操作.
该声明:
IsXML == true ? PopulateRegister(ParseType.Xml) : PopulateRegister(ParseType.Str);
Run Code Online (Sandbox Code Playgroud)
如果方法PopulateRegister返回一个值,并且您将该值赋给某个值,则该值有效.例如,这将是有效的:
string result = (someCondition) ? "condition is true" : "condition is false";
Run Code Online (Sandbox Code Playgroud)
您可能希望以这种方式使用条件(请注意,我们使用ParseType枚举值作为条件的返回类型,并且它充当您的方法的参数):
PopulateRegister((IsXML) ? ParseType.Xml : ParseType.Str);
Run Code Online (Sandbox Code Playgroud)
请注意,上述内容是可行的,但可能会产生难以理解/调试/维护的代码,并且通常不会被视为最佳实践.