c# - 访问空值会导致应用程序失败/C#

标签 c# reflection null

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

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

当应用程序在该时刻中断时,属性表示 ProductNumber(它是一个 string),其值为 Product 对象,其值为 ProductNumber = null,所以我尝试了这样的方法:

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

但无论如何它坏了..

如何改进这段代码以避免破坏?

谢谢

干杯

最佳答案

似乎 output.Append 提示 null 值。这里有 2 可能的令人讨厌的 null 来源:

  1. property.GetValue(this) 返回 null,因此 ?. 位于 ?.ToString() < em>传播 null
  2. ToString() 本身返回 null(几乎没有这种情况,但仍然有可能)

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

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

最终代码为

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

关于c# - 访问空值会导致应用程序失败/C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197611/

相关文章:

c# - GC压力——List vs Array,class vs struct

go - 检查 interface{} 上的 reflect.Kind 返回无效结果

c# - 反射 PropertyInfo.GetValue 来自集合

sql-server - 恢复数据库 SQL Server - 数据为空,不能对空值调用此方法或属性

null - BigQuery - 过滤不丢失 'null' 值

c++ - HBITMAP hbm = LoadImage函数返回NULL

c# - ServiceStack 中是否有任何等效于 ValidateAntiForgeryToken 的东西?

C# 代码样式 : Switching from "this." prefix to "underscore"

c# - Winform Webbrowser 被识别为移动设备

c# - 如何反射性地判断属性是否具有公共(public) Setter