为什么我不能使用'??' System.DBNull 值的操作数?
我有一个 Oracle 数据表,获取的列为空。所以我想保持代码的美观和简单,我会使用 ??操作数。 AlternatePhoneNumber 是我的 C# 模型中的一个字符串。
AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""
但是,即使使用该代码我仍然收到错误。
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
我知道该错误意味着什么,但为什么?不能在 DBNull 上使用? null 和 DBNull 本质上不是一样的吗?
谢谢。
I have an Oracle data table fetching columns that be null. So I figure to keep the code nice and simple that I'd use the ?? operand. AlternatePhoneNumber is a string in my C# model.
AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""
However, even with that code I still get the error.
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
I know what the error means but why is ?? not usable on DBNull? Isn't null and DBNull essentially the same?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
??
运算符仅适用于实际的null
。null
和DBNull.Value
不同;DBNull.Value
只是一个占位符对象。此外,该异常来自
AlternatePhoneNumber
属性内部,在??
运算符执行之前。 (您的代码没有强制转换)。如果
customer
是类型化数据集中的一行,请在设计器中更改该列的NullValue
属性。The
??
operator only applies to actualnull
s.null
andDBNull.Value
are not the same;DBNull.Value
is simply a placeholder object.Also, that exception is coming from inside the
AlternatePhoneNumber
property, before your??
operator executes. (Your code doesn't have a cast).If
customer
is a row in a typed dataset, change the column'sNullValue
property in the designer.null 和 DBNull 不一样。 System.DBNull 是一个实际对象。
null and DBNull are not the same. System.DBNull is an actual object.
问题是
AlternatePhoneNumber
是一个字符串。 DBNull 不是。试试这个:
The problem is that
AlternatePhoneNumber
is a string. DBNull is not.Try this instead:
这样做:
Do this:
DBNull 是具有单个值的类型,与空字符串引用不同,这就是为什么不能使用
??
的原因。不过你可以这样做:DBNull is a type with a single value, and is not the same as a null string reference, which is why you can't use
??
. You could do this however:正如其他回复所述,
null
表示不引用任何对象的引用,而DBNull
是 ADO.NET 提供的一个类,用于指示何时数据库(或数据表)中的字段或值为 NULL。虽然您可以使用 条件(三元)运算符 (?: ) 做你想做的事:
我倾向于将其包装在 扩展方法:
我发现它使代码更易于阅读和理解。
As other replies state,
null
means a reference that refers to no object, whileDBNull
is a class supplied by ADO.NET to indicate when a field or value is NULL at the database (or in a DataTable).While you can use the conditional (ternary) operator (?:) to do what you want:
I tend to wrap this up in an extension method:
which I find makes the code easier to read and understand.
DBNull 不是真正的“空”。
这 ”??” - 运算符仅检测空引用,而不检测模拟“空”行为的对象。
DBNull is NOT a real "null".
The "??" - operator detects only null - references, not objects that emulate "null" behavior.