StringBuilder.Append 问题
我想知道 :
StringBuilder sb = new StringBuilder();
sb.Append("xxx");
sb.Append("yyy");
sb.Append("zzz");
和 :之间的区别(如果有的话)
StringBuilder sb = new StringBuilder();
sb.Append("xxx")
.Append("yyy")
.Append("zzz");
I would like to know the difference (if there is any) between :
StringBuilder sb = new StringBuilder();
sb.Append("xxx");
sb.Append("yyy");
sb.Append("zzz");
And :
StringBuilder sb = new StringBuilder();
sb.Append("xxx")
.Append("yyy")
.Append("zzz");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有区别,后一种情况称为“流利语法”。
There's no difference, the latter case is called 'Fluent Syntax'.
没有功能上的区别。在第一种情况下,您在三个语句中以相同的顺序将字符串附加到相同的
StringBuilder
中。在第二种情况下,您将在一条语句中将相同的字符串附加到相同的StringBuilder
中。不会有显着的性能差异,也绝对没有可观察到的差异。您可以从风格上选择其中之一。
There is no functional difference. In your first case, you're appending strings to the same
StringBuilder
in the same order in three statements. In your second case, you're appending the same strings to the sameStringBuilder
in one statement.There will be no notable performance difference and absolutely no observable difference. You may choose one or the other stylistically.
两者之间的 IL 肯定会有所不同,并且从第一眼看来,链接版本可能会快几个纳秒(我只是喜欢说纳秒。),但是无需考虑重构代码。如果一种方式看起来更干净,我会选择那条路。
它总是困扰着我,
StringBuilder.Append
总是会返回自身。它使人们认为 StringBuilder 是一种不可变的结构,而实际上它绝对不是。这在 F# 中也特别烦人,您必须显式忽略它返回的内容。但要做什么呢?The IL surely will look differently between the two, and just from first looks, the chained version may be a few nanoseconds faster (I just like saying nanoseconds.), but it's nothing to consider refactoring your code over. If it looks cleaner one way, I'd take that path.
It always bugged me, how
StringBuilder.Append
would always return itself. It causes one to think that the StringBuilder is an immutable structure, when it most definitely is not. It is also especially annoying in F#, where you have to explicitly ignore what it returns. But whatcha gonna do?它们之间没有区别。但您可以使用第二个来减少代码行:)
There is no difference between them. But you can use second one for less code line :)