空字符串(如果为null) [英] Empty string if null

查看:210
本文介绍了空字符串(如果为null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有这个

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

当它返回null时,它给出一个错误,如何使CustomerID为空字符串,如果它为null?

It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?

/M

推荐答案

(C#6.0更新)

如果您使用的是C#6或更高版本(Visual Studio 2015或更高版本),则可以使用

If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.:

var customerId = cu.Customer?.CustomerId.ToString() ?? "";

空条件运算符的一个有用的属性是,如果您要测试多个嵌套属性是否为空,也可以将其链接":

One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:

// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";

对于 6.0之前的C#版本(VS2013或更早版本),您可以像这样合并它:

For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:

string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";

在尝试访问其成员之前,只需检查对象是否为非null,否则返回空字符串.

Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.

除此之外,在某些情况下空对象模式很有用.这将意味着您确保Customer的父类(在这种情况下为cu的类型)始终返回对象的实际实例,即使该对象是"Empty"也是如此.如果您认为此链接可能适用于您的问题,请查看此示例:

Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer's parent class (type of cu in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.

这篇关于空字符串(如果为null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆