c# - 合并与空字符串连接

标签 c# string concatenation coalesce

我的同事是 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/

相关文章:

c# - 在 c# 中使用 iTextSharp 在 pdf 中使用阿拉伯语

c# - __makeref 作为在 C# 中获取引用值的一种方式?

silverlight - 在 XAML 中的一个 TextBlock 中格式化多个绑定(bind)字段

python - 交换字符串中的大写和小写

list - 连接列表并将结果返回到第一个参数

python - 有什么方法可以从两个数据帧创建一个新的数据帧,其中一个 df 的每一行都必须重复?

c# - Parallel.Foreach 问题

c# - ParameterInfo.IsLcid 或 ParameterInfo.IsRetval 何时为真?

C# split 函数不起作用

arrays - 如何连接两个字符串以创建变量名称