首页 > 解决方案 > 访问空值导致应用程序失败/C#

问题描述

我只是循环并将我的属性附加到一个大字符串中:

output.Append(property.GetValue(this).ToString()));

当应用程序在那一刻中断时,属性表示 aProductNumber是 a string, this 的值是Product具有 值的对象ProductNumber = null,所以我尝试了这样的事情:

output.Append(property.GetValue(this)?.ToString()));

但无论如何它打破了..

我怎样才能改进这段代码以避免在那里中断?

谢谢

干杯

标签: c#reflectionnull

解决方案


似乎output.Append 抱怨null价值观。这里有2pesky 的可能来源null

  1. property.GetValue(this)返回null因此?.传播?.ToString() null
  2. ToString()本身返回null(几乎没有,但仍有可能)

我们可以使用运算符解决这两种可能性??:让我们返回一个空字符串,无论其来源null是:

property.GetValue(this)?.ToString() ?? ""

最终代码是

output.Append(property.GetValue(this)?.ToString() ?? "");

推荐阅读