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

问题描述

我从DB获得DBNull结果。

I'm getting DBNull results from DB.

尝试申请??

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

field1 = DBNull

field1 = DBNull

field2 = 4

field2 = 4

但是它不起作用,返回{},因为result [ field1]不为null(它是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?

仅以这两个字段为例,实际上会有更多字段,而我尝试先获取非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...)

抱歉,我的错。

解决方案

按照彼得·范德·海因登的解答,说我从数据库中获得

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

result [ field1] = DBNull

result["field1"] = DBNull

result [ field2] = DBNull

result["field2"]= DBNull

result [ field3] = 4

result["field3"] = 4

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

将返回{}(第一个不为null,DBNull为... ...不为空)

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

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

将按预期返回结果[ field3] = 4。

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

int?可以用您得到的任何结果类型(例如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的结果)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:05