本文介绍了String.Format vs +运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更好,哪个更快,哪个更容易等... ?????

String.Format(" yadda {0} yadda {1}" ;,x,y)


" yadda" + x.ToString()+" yadda" + y.tostring();

我的代码有两种混合物,如果我要标准化

,我还会感到很好吗?

Thnanks,


JIM

解决方案



除了其他海报提到的内容外,请记住,如果您想要将代码国际化,那么+ "操作员方式是

非首发。




在某些情况下我同意,但在许多情况下,通过不调用ToString()可以大大提高可读性,在这种情况下OP''示例缩小downto


string s =" yadda" + x + yadda + y;


我认为它更具可读性(语法着色会使它更具可读性)比


string s = string。格式(yadda {0} yadda {1},x,y);

PS!如果字符串连接的任何部分包含字符串文字,ToString()也会在其他部分自动调用。


-

快乐编码!

Morten Wennevik [C#MVP]




嗨Jim,


IIRC,连接速度更快,但你应该选择基础关于你是否实际上需要在连接字符串时获得速度(即你的应用程序性能是否很重要)然后决定是否应该牺牲
牺牲代码可读性略有提升。


-

Tom Spink

爱丁堡大学


Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should standardize
or not ??
Thnanks,

JIM

解决方案

In addition to what other posters have mentioned, keep in mind that if
you ever want to internationalize your code, the "+" operator way is a
non-starter.


In some cases I agree, but in many cases readability can be much improved by not calling ToString(), in which case the OP''s example narrows downto

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even more readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string literal, ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]



Hi Jim,

IIRC, concatenation is faster, but you should choose based on whether you
actually need to gain speed when concatenating strings (i.e. is your
application performance critical) and then decided whether you should
sacrifice code readability for a slight performance improvement.

--
Tom Spink
University of Edinburgh



这篇关于String.Format vs +运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 04:01