我只是循环并将我的属性附加到一个大字符串中:
output.Append(property.GetValue(this).ToString()));
当应用程序在该时刻中断时,属性表示 ProductNumber
(它是一个 string
),其值为 Product
对象,其值为 ProductNumber = null
,所以我尝试了这样的方法:
output.Append(property.GetValue(this)?.ToString()));
但无论如何它坏了..
如何改进这段代码以避免破坏?
谢谢
干杯
最佳答案
似乎 output.Append
提示 null
值。这里有 2
可能的令人讨厌的 null
来源:
property.GetValue(this)
返回null
,因此?.
位于?.ToString()
< em>传播null
ToString()
本身返回null
(几乎没有这种情况,但仍然有可能)
我们可以使用 ??
运算符解决这两种可能性:无论 null
的来源是什么,我们都返回一个空字符串:
property.GetValue(this)?.ToString() ?? ""
最终代码为
output.Append(property.GetValue(this)?.ToString() ?? "");
关于c# - 访问空值会导致应用程序失败/C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197611/