我正在从Web服务获得SOAP消息的响应。我事先并不知道哪些节点可用(有些但不是全部)。 假设我获得了有关客户的数据
名称
城市
在代码中我可以写
string name = "";
string city = "";
name = customer.name;
city = customer.city;
如果城市返回一个空字符串,我可以通过编写
来处理city = (string)customer.city;
代替。但有时响应不包括城市节点,然后我得到NullReferenceException未处理的错误,我该如何解决这个问题?
答案 0 :(得分:1)
你真的要求这个:
city = customer != null ? customer.city : "";
顺便提一下,将string
投射到string
,就像你在这里一样:(string)""
((string)customer.City
时候customer.City == ""
的等价物是没有必要的。 (当然,除非customer.City
实际上不是string
。)
答案 1 :(得分:0)
你也可以用??运营商。这假设客户对象始终不为空。
string city = customer.city ?? ""