将字符串转换为枚举

时间:2013-06-26 19:00:45

标签: c# casting enums

我在C#中有一个调用存储过程的方法,并用值填充DataTable。我有一个问题,我的存储过程的返回值是一个字符串,而我用来保存我的C#中的值的属性来自类型为枚举的类。我尝试施放,但我一直收到这个错误:

  

指定的演员表无效。

这是我调用存储过程的方法:

public void GetOrder()
{
    ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["T_DB"];
    string conString = connectionString.ConnectionString;

    DataSet ds = new DataSet();

    using ( SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand("LH_Get_order", con);
        cmd.Parameters.AddWithValue("@onum", 45642);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        ad.Fill(ds);

        if (ds.Tables[0].Rows.Count > 0)
        {
            this.BatchId = ds.Tables[0].Rows[0]["gbo_batch_id"].ToString();
            this.ExternalRefId = ds.Tables[0].Rows[0]["o_num"].ToString();
            this.LoanId = ds.Tables[0].Rows[0]["o_loan"].ToString();
            this.OrderType = (eOrderType)ds.Tables[0].Rows[0]["OrderType"]; //problem
        }
    }
}

此行出现问题:

this.OrderType = (eOrderType)ds.Tables[0].Rows[0]["OrderType"];

这是我的OrderType财产:

public eOrderType OrderType
{
    get { return _OrderType; }
    set { _OrderType = value; }
}

这是eOrderType枚举:

public enum eOrderType : int {

    [System.Runtime.Serialization.EnumMemberAttribute(Value="CVA BPO")]
    CVABPO = 1,

    [System.Runtime.Serialization.EnumMemberAttribute()]
    ExteriorBPO = 2,

    [System.Runtime.Serialization.EnumMemberAttribute()]
    Inspection = 3,

    [System.Runtime.Serialization.EnumMemberAttribute()]
    RepairEstimate = 4,
}

2 个答案:

答案 0 :(得分:0)

您需要将字符串解析为枚举值而不是转换:

eOrderType orderType;
if(Enum.TryParse(ds.Tables[0].Rows[0]["OrderType"], out orderType))
{
    this.OrderType = orderType;
}
else
{
    //parse failed
}

答案 1 :(得分:0)

(eOrderType) Enum.Parse(typeof(eOrderType ),ds.Tables[0].Rows[0]["OrderType"]);