0

我有一个简单的 C# 语句:

var code = container.thing.result.decode ?? "Unknown";

这会引发“未设置对象实例的对象引用”。数据库值为空时的异常。它与非空值完美地工作(到目前为止)。我尝试更明确并用三元运算符重写了该行:

var outcome = container.thing.result.decode == null ? "Unknown" : container.thing.result.decode;

我得到了相同的结果,但有相同的异常(ReSharper 引导我回到更简单的 ?? 语句)。

我也读到了??运算符仅适用于可为空的类型。我正在使用的字段不是可为空的类型,它是 nvarchar(100) 并且也是查找表的外键。正如我上面所说,该语句适用于有效的非空值。

应用程序的 ORM 也有一个 CODE 值,以形成一个 CODE 和 DECODE 对,看起来它应该映射到查找表。

但我不知道如何处理空值。

谢谢!

编辑:感谢您的快速回复!我确实在发布后几分钟就弄清楚了我在哪里感到困惑。我认为把问题写出来有助于我描述问题。我更改了语句以检查引用查找表的实际字段是否为空:

var outcome = container.thing.database_code_field == null ? "Unknown" : container.thing.result.Decode;

这看起来像我想要的。再次感谢你!

4

3 回答 3

5

You'll get an exception if any of the following is null:

  • container
  • container.thing
  • container.thing.result

We can't tell which of those values is null in your situation, or whether null is a valid value. You should work that out and then either fix whatever's giving you a null value, or write code to handle that case.

于 2012-04-12T18:34:58.507 回答
4

You need to step through your entire member hierarchy.

For example, if container is null, then you cannot access container.thing. And if container.thing is null, you cannot access container.thing.results, etc.

It is not enough to simply catch the case where the very last member is null.

于 2012-04-12T18:36:24.063 回答
0

The problem is that container, thing, or result is null, not decode. If decode was null then the ?? operator would set the string appropriately.

?? is a function that takes some nullable value and a non-null value to replace it. The entire left hand side of the ?? operator needs to be evaluated to pass it into that function, and if one of the previously mentioned variables is null it doesn't even get that far.

于 2012-04-12T18:35:22.830 回答