字段类型变量 - C#应用数据集
问题描述:
说我有从存储在一个变量,像这样的SQL查询包含值这个字符串变量:字段类型变量 - C#应用数据集
string strDesc = ds.Tables[0].Rows[0]["Description"].ToString();
,并为一个字符串它工作正常
什么关于如果我的数据库中的字段类型是int和int类型的,我将如何像上面那样应用它?难道不会停像下面应用了转换?:
的int字段我想保持它作为一个int
int strOrderID = ds.Tables[0].Rows[0]["OrderID"];
钱场我想保持类型钱
decimal strPrice = ds.Tables[0].Rows[0]["Price"];
谢谢提前提供任何答案
答
我建议使用强类型的Field
扩展方法,它也支持可空类型:
int orderID = ds.Tables[0].Rows[0].Field<int>("OrderID");
decimal price = ds.Tables[0].Rows[0].Field<decimal>("Price");
假设Price
可以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;
}
}
+1我想更进一步,定义一个简单的类,它将'DataRow'与包含字符串文字和适当类型的编译时属性一起定义。 –