我的同事是 C# 新手,不了解合并运算符。于是,我看到他写了这样一行代码:
string foo = "" + str;
想法是,如果 str 为 null,则此表达式将返回一个空字符串。当然,也可以改写为:
string foo = str ?? "";
而且我觉得这样会更具可读性。但这真的有那么重要吗?可读性的好处是否足以建议返回并使这些行看起来像第二行?还是这是我应该学会放手的事情之一(前提是我的同事接受了将来最好的方法的教育)?
编辑:请注意,我很欣赏效率评论,但这并没有真正用于任何对性能至关重要的情况。因此,尽管这些信息很有趣,但我认为它不一定重要。
最佳答案
IMO,最好明确定义这样的逻辑,即不要使用字符串连接来避免空字符串并使用条件语句或 ??运营商。
关于其他评论:
there is also a performance benefit to using the null-coalescing operator, since no concatenation need take place (and, therefore, no extra string instance is being created unnecessarily)
不是真的。 C# 编译器将 ""+ string2 编译为与 string1 100% 相同的代码?? “”。此外,C# 编译器将 + 运算符转换为调用 string.Concat 方法,后者又使用 string.IsNullOrEmpty 函数检查参数,并且在这种情况下不分配新字符串。
Also I would recommend the use of String.Empty over "" as it is a constant and does not require the creation of a new String
.NET 框架支持 string interning所以 ""和 string.Empty 指向同一个内存区域
关于c# - 合并与空字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/416473/