你能帮帮我C#switch case吗?

时间:2016-08-08 10:33:15

标签: c# switch-statement case

我有代码C#switch case

public void gdvDetail_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
{
    try
    {
        DataRowView oRow = (DataRowView)(gdvDetail.GetRow(e.ListSourceRowIndex));
        switch (e.Column.Name)
        {
            case colQuotaQuantity.Name:
                if (colQuotaQuantity.UnboundExpression == "" && oRow.Row.Table.Columns.Contains("QuotaQuantity"))
                {
                    e.Value = oRow.Row["QuotaQuantity"];
                }
                break;
                //e.Value = oRow.Row("Quantity")
            case colDifferenceQuantity.Name:
                if (oRow.Row.Table.Columns.Contains("QuotaQuantity") && !Information.IsDBNull(oRow.Row["QuotaQuantity"]) && !Information.IsDBNull(oRow.Row["Quantity"]))
                {
                    e.Value = System.Convert.ToDouble(oRow.Row["Quantity"]) - System.Convert.ToDouble(oRow.Row["QuotaQuantity"]);
                }
                break;
        }
    }
    catch (Exception ex)
    {
        CommonFunction.ShowExclamation(ex.Message);
    }
}

当我尝试编译应用程序时,收到以下错误:

  

预计值为常数   line:case colQuotaQuantity.Name:
  line:case colDifferenceQuantity.Name:

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

switch/case语句中的值必须是编译时常量,如数值或字符串文字:

switch(i)
{
    case 0: /*...*/ break;
    case 1: /*...*/ break;
}

switch(s)
{
    case "hello": /*...*/ break;
    case "world": /*...*/ break;
}

无法使用变量,因为它们的值仅在运行时中已知,而在编译时未知。因此case colDifferenceQuantity.Name:在C#中无效。

您将此代码转换为if语句:

if (e.Column.Name == colQuotaQuantity.Name)
{
    /* ... */
}
else if (e.Column.Name == colDifferenceQuantity.Name)