如果声明“无效的表达式术语'其他'

时间:2014-01-26 17:50:32

标签: c# asp.net

当我尝试编译时,以下代码给出了一个错误“无效的表达式术语'else'”。我无法弄清楚如何解决它:

public double CalcTicketCost(int section, double quantity)
{
    double amount = 0;

    if (int.Parse(lstSectionNumber.SelectedItem.Value) < 150)
    {
        amount = premiumTicket  * quantity;
        return amount;
    }
    {
        else  (int.Parse(lstSectionNumber.SelectedItem.Value) > 150) // This line is where the problem seems to be

        amount = basicTicket * quantity; 
    }
    return amount;
}

2 个答案:

答案 0 :(得分:5)

}之前有else,语法应该是......

if (condition)
{
    // condition is true
}
else
{
    // condition is false
}

但是,您else之后还有第二个条件,因此这应该是else if

if (condition1)
{
    // condition1 is true
}
else if (condition2)
{
    // condition1 is false, condition2 is true
}

此外,您的第一个return amount不是必需的;你可以写这样的方法:

public double CalcTicketCost(int section, double quantity)
{
    double amount = 0;

    if (int.Parse(lstSectionNumber.SelectedItem.Value) < 150)
    {
        amount = premiumTicket * quantity;
    }
    else if (int.Parse(lstSectionNumber.SelectedItem.Value) > 150)
    {
        amount = basicTicket * quantity; 
    }

    return amount;
}

您可以在documentation that explains this in more detail找到MSDN以及更多内容。

但是,您的代码可能包含错误。如果lstSectionNumber.SelectedItem.Value 等于 150,会发生什么?目前,您的方法将返回0。这是理想的行为吗?

答案 1 :(得分:2)

if
 {}
else{}

 if {}
{ else } }