由网友(称霸幼儿园)分享简介:如果我有code类似以下内容:If I have code similar to the following:while(myDataReader.Read()){myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);}这引发错误:I...
如果我有code类似以下内容:
If I have code similar to the following:
while(myDataReader.Read())
{
myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}
这引发错误:
It throws the error:
对象不能从DBNull转换为其他类型。
Object cannot be cast from DBNull to other types.
定义 INTVAL
作为一个可空int是不是一种选择。有没有办法为我做以上?
defining intVal
as a nullable int is not an option. Is there a way for me to do the above?
推荐答案
你能使用的扩展方法? (注销我的头顶部)
Can you use an extension method? (written off the top of my head)
public static class DataReaderExtensions
{
public static T Read<T>(this SqlDataReader reader, string column, T defaultValue = default(T))
{
var value = reader[column];
return (T)((DBNull.Value.Equals(value))
? defaultValue
: Convert.ChangeType(value, typeof(T)));
}
}
您会使用它,如:
while(myDataReader.Read())
{
int i = myDataReader.Read<int>("mycolumn", 0);
}
相关推荐
最新文章