合并vs空字符串串联 [英] Coalesce vs empty string concatenation

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

问题描述

我的同事是C#的新手,不了解合并运算符。因此,我看到他写了这样的代码行:

My coworker is new to C# and didn't know about the coalesce operator. So, I saw him write a line of code like this:

string foo = "" + str;

这样的想法是,如果str为null,则此表达式将返回一个空字符串。当然,可以这样重写:

The idea being that if str is null, this expression would return an empty string. Of course, that could be rewritten as this:

string foo = str ?? "";

我觉得这样可读性更好。但这真的有什么大不了的吗?可读性好处是否足以建议您退后并使这些行看起来像第二行?还是这是我应该学会放手的事情之一(前提是我的同事受过将来最好的方法教育)?

And I feel that would be more readable. But is it really that big a deal? Are the readability benefits enough to suggest going back and making those lines look like the second? Or is this one of those things that I should learn to let go (provided that my coworker is educated on the best way to do this in the future)?

编辑:仅需注意,我感谢效率方面的评论,但这在性能至关重要的情况下并没有真正使用。因此,尽管该信息很有趣,但不一定是我认为重要的事情。

EDIT: Just a note, I appreciate the efficiency comments, but this isn't really being used in any situations where that performance would be critical. So while that info is interesting, it's not necessarily what I feel is important.

推荐答案

IMO,更好地进行定义这样的逻辑,即不使用字符串连接来避免空字符串,而使用条件语句或?

IMO, it is much better to clearly define such logic i.e. don't use string concatenation to avoid null string and use conditional statement or ?? operator.

关于其他注释:



使用null-coalescing运算符
,因为不需要进行串联
(因此,不需要创建额外的字符串
实例

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函数检查参数,并且在这种情况下不分配新的字符串。

Not true. C# compiler compiles "" + string2 to the 100% same code as string1 ?? "". Moreover C# compiler translates + operator to call to string.Concat method which in turn checks arguments with string.IsNullOrEmpty function and doesn't allocate a new string in this case.


我也建议使用
String.Empty,因为它是
常量,不需要
创建新的字符串

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.Empty指向相同的内存区域

.NET framework supports string interning so "" and string.Empty point to the same memory region

这篇关于合并vs空字符串串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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