从 IDataReader 获取值的空安全方法
(LocalVariable)ABC.string(Name) = (IDataReader)dataReader.GetString(0);
此名称
值来自数据库。
如果这个 name
为 null
时会发生什么,而读取它会引发异常?
我在这里手动执行一些 if 条件。我不想编写手动条件来检查所有变量。
我现在正在做这样的事情..
String abc = dataReader.GetValue(0);
if (abc == null)
//assigning null
else
//assigning abc value
我们可以为此编写扩展方法吗?
(LocalVariable)ABC.string(Name) = (IDataReader)dataReader.GetString(0);
This name
value is coming from database.
What happening here is if this name
is null
while reading it's throwing an exception?
I am manually doing some if condition here. I don't want to write a manual condition to check all my variables.
I am doing something like this now..
String abc = dataReader.GetValue(0);
if (abc == null)
//assigning null
else
//assigning abc value
Is there something like can we write extension method for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有几个扩展方法,它们可以很好地解决您从数据读取器检索强类型值方面的所有问题。如果值为 DbNull,则将返回该类型的默认值。如果
string
是一个类,则将返回null
。如果该字段为int
,则将返回0
。此外,如果您需要一个int?
,例如来自可为 null 的 int 字段,则将返回null
。Kumar 案例的具体用法:
用法
或
一般
扩展
来自 http://skysanders.net/subtext/archive/2010/03/02/generic-nullsafe-idatarecord-field-getter.aspx
Here is a couple extension methods that will nicely wrap up all of your concerns around retrieving strongly typed values from a data reader. If the value is DbNull the default of the type will be returned. In the case of
string
which is a class, anull
will be returned. If the field wasint
, then0
would be returned. Additionally, if you are expecting anint?
, say from an nullable int field,null
would be returned.Specific Usage for Kumar's case:
General Usage
or
or
Extension
from http://skysanders.net/subtext/archive/2010/03/02/generic-nullsafe-idatarecord-field-getter.aspx
与 @sky-sanders 的答案类似,但对转换不太严格:
Similar to @sky-sanders answer but less strict with conversions:
我的解决方案是:
当,
Status = GetValue(currentDataRow["status"])
My solution is that:
When,
Status = GetValue<string>(currentDataRow["status"])
结合顶级解决方案和建议,这是一个 C# 6 箭头表达式 版本,支持
GetValue
和GetValueOrDefault
以及可选默认值值参数。Combining top solutions and suggestions, here is a C# 6 arrow expression version with support for
GetValue<T>
andGetValueOrDefault<T>
with optional default value parameters.我会用这样的东西:
I'd use something like this: