我喜欢使用DataTable而不是DataReader。我讨厌重复的样板,所以我在DataRow类中添加了一些扩展方法来封装downcast逻辑并使代码更具可读性:
DataTable dt = ExecStoredProcedure() ;
foreach ( DataRow dr in dt )
{
int id = dr.CastAsInt("id") ;
dateTime? dtLastUpdated = dr.CastAsDateTimeNullable("last_update_date") ;
int? col3 = dr.CastASIntNullable(3) ;
}这里是将DataRow中的列值向下转换为int / int?的代码:
#region downcast to int
public static int CastAsInt( this DataRow row , int index )
{
return toInt( row[index] ) ;
}
public static int CastAsInt( this DataRow row , string columnName )
{
return toInt( row[columnName] ) ;
}
public static int? CastAsIntNullable( this DataRow row , int index )
{
return toIntNullable( row[index] );
}
public static int? CastAsIntNullable( this DataRow row , string columnName )
{
return toIntNullable( row[columnName] ) ;
}
#region conversion helpers
private static int toInt( object o )
{
int value = (int)o;
return value;
}
private static int? toIntNullable( object o )
{
bool hasValue = !( o is DBNull );
int? value = ( hasValue ? (int?) o : (int?) null ) ;
return value;
}
#endregion conversion helpers
#endregion downcast to int我确定从DataReader挂起类似的扩展方法会相当简单。