c# - 访问空值导致应用程序失败/C#
问题描述
我只是循环并将我的属性附加到一个大字符串中:
output.Append(property.GetValue(this).ToString()));
当应用程序在那一刻中断时,属性表示 aProductNumber
是 a string
, this 的值是Product
具有 值的对象ProductNumber = null
,所以我尝试了这样的事情:
output.Append(property.GetValue(this)?.ToString()));
但无论如何它打破了..
我怎样才能改进这段代码以避免在那里中断?
谢谢
干杯
解决方案
似乎output.Append
抱怨null
价值观。这里有2
pesky 的可能来源null
:
property.GetValue(this)
返回并null
因此?.
传播?.ToString()
null
ToString()
本身返回null
(几乎没有,但仍有可能)
我们可以使用运算符解决这两种可能性??
:让我们返回一个空字符串,无论其来源null
是:
property.GetValue(this)?.ToString() ?? ""
最终代码是
output.Append(property.GetValue(this)?.ToString() ?? "");