什么是开始使用C#从返回的DataRow类型推荐的方法是什么? [英] What's the recommended way to start using types from a returned DataRow in C#?
问题描述
在通过一个DataRow循环和遇到的类型,如
When looping through a DataRow and encountering types such as
DataRow dr;
dr["someString"]
dr["someInteger"]
dr["somedata"]
什么是让他们到他们相应的数据类型的最好方法是什么?博士[富]仅仅是一个普通的对象。
What's the best way to get them into their corresponding data types? dr["foo"] is just a generic object.
此外,这些都能够方便地转换为可空类型?博士[someInteger]可能为空。
Also, are these able to be easily converted to nullable types? dr["someInteger"] could be null.
推荐答案
这是一个DataRow读取数据时,你最大的敌人是空值。在的DataRow
,当值为null,它不等于空:它等于的DBNull.Value
When reading from a DataRow, your biggest enemy is a null value. In a DataRow
, when a value is null, it is not equals to null: It is equals to DBNull.Value
.
if(DBNull.Value == null)
{
// Will never happen
}
除非你知道你的领域不能为空,这是不安全的施放。例如,如果数据是DBNull的下面的例子中将会失败:
Unless you know that your field cannot be null, it is not safe to cast. For example, the following example will fail if the data is DBNull:
string name = (string)dr["Name"];
如果您可以使用LINQ的扩展,可以包括参照 System.Data.DataSetExtensions
和命名空间 System.Data这
和呼叫
If you can use the LINQ extensions, you can include the reference System.Data.DataSetExtensions
and the namespace System.Data
and call
string name = dr.Field<string>("Name");
如果您不能使用LINQ,那么你有回落,为空值检查与
If you cannot use LINQ, then you have to fall back to checking for null value with
string name = null;
if(!dr.IsNull("Name"))
name = (string)dr["Name"];
或者你可以code这样你自己的领域的功能:
Or you could code your own Field function like this:
public static T GetValue<T>(object value)
{
if (value == null || value == DBNull.Value)
return default(T);
else
return (T)value;
}
和让你的价值是这样的:
and get your value this way:
string name = GetValue<string>(dr["Name"]);
这篇关于什么是开始使用C#从返回的DataRow类型推荐的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!