C# ??带有 DBNull 的运算符(类似 Coalesce 的结果) [英] C# ?? operator with DBNull (Coalesce-like result)

查看:16
本文介绍了C# ??带有 DBNull 的运算符(类似 Coalesce 的结果)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 DB 得到 DBNull 结果.

I'm getting DBNull results from DB.

尝试申请??运营商喜欢它

Trying to apply ?? operator to it like

result["field1"] ?? result["field2"]

field1 = DBNull

field1 = DBNull

field2 = 4

但它不起作用,返回 {} 因为 result["field1"] 不为空(它是 DBNull).我希望从中得到 4.

but it doesn't work, returns {} because result["field1"] is not null (it's DBNull). I expect to get that 4 from it.

尝试过

result["field1"] = null

首先,但是不行,还是DBNull类型.

first, but it doesn't work, it's still DBNull type.

问题是如何处理,以某种方式将 DBNull 转换为 null?怎么做 ??运算符使用 DBNull 值?

The question is how to handle this, convert DBNull to null in some way? How to make ?? operator work with DBNull values?

更准确地说:

有没有办法获得类似COALESCE的行为?

Is there a way to get COALESCE-like behaviour?

这 2 个字段只是举例,实际上会有更多的字段,我试图先不为 null(所以我希望使用链接 field1 ?? field2 ?? field3...)

That 2 fields are just for example, in reality there will be much more fields and I'm trying to get first not null (so I was hoping to use chaining field1 ?? field2 ?? field3...)

我没说清楚,抱歉,我的错.

I wasn't precise with that, sorry, my fault.

解决方案

按照 Peter van der Heijden 的解决方案,说我来自 DB

Following Peter van der Heijden solution, say I'm getting from DB

result["field1"] = DBNull

result["field1"] = DBNull

result["field2"]= DBNull

result["field2"]= DBNull

结果["field3"] = 4

result["field3"] = 4

result["field1"] ?? result["field2"] ?? result["field3"]

将返回 {}(首先不是 null,DBNull 是......好吧......不是 null)

will return {} (first not null, DBNull is ... well ... not null)

但是

result["field1"] as int? ?? result["field2"] as int? ?? result["field3"] as int?

将按预期返回 result["field3"] = 4.

will return result["field3"] = 4, as expected.

内部?可以替换为您获得的任何结果类型(例如 DateTime?).

int? can be replaced with whatever result type you get (like DateTime? for example).

推荐答案

我倾向于这样做:

string s = result["field1"] as string;

int? i = result["field2"] as int?;

或者在您的情况下:

string s = result["field1"] as string ?? result["field2"] as string;

这篇关于C# ??带有 DBNull 的运算符(类似 Coalesce 的结果)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆