0

假设我有这个字符串变量,其中包含来自 SQL 查询的值,存储在一个变量中,如下所示:

string strDesc = ds.Tables[0].Rows[0]["Description"].ToString();

作为一个字符串,它可以正常工作

如果我在数据库中有类型为 int 和 money 的字段类型,我将如何像上面那样应用它?应用转换后会不会像下面这样?:

int 字段我想将其保留为 int

int strOrderID = ds.Tables[0].Rows[0]["OrderID"];

我想保留为货币类型的货币字段

decimal strPrice = ds.Tables[0].Rows[0]["Price"];

提前感谢您提供的任何答案

4

1 回答 1

2

我建议使用Field也支持可空类型的强类型扩展方法:

int orderID = ds.Tables[0].Rows[0].Field<int>("OrderID");
decimal price = ds.Tables[0].Rows[0].Field<decimal>("Price");

假设Pricecan NULL,您可以Nullable<decimal>轻松地将其转换为:

decimal? price = ds.Tables[0].Rows[0].Field<decimal?>("Price"); 
if(price.HasValue) Console.WriteLine(price.Value);

顺便说一句,旧的方法是简单的铸造:

int orderID = (int) ds.Tables[0].Rows[0]["OrderID"];

但是,如果您多次使用此查询并且选择单个表或至少属于一起的字段,则应考虑创建具有这些属性的类。然后,您的代码变得更具可读性、可重用性和可维护性。

public class Order
{
    public int OrderID { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }

    public override bool Equals(object obj)
    {
        Order o2 = obj as Order;
        if (o2 == null) return false;
        return OrderID == o2.OrderID;
    }
    public override int GetHashCode()
    {
        return OrderID;
    }
    public override string ToString()
    {
        return Description;
    }
}
于 2013-07-14T21:28:21.950 回答