cho*_*bo2 26 .net c# asp.net string
我一直在想这个问题.为什么使用String.Concat()而不是使用plus运算符.我理解String.Format,因为它使用plus运算符空洞并使您的代码看起来更好.
比如说
string one = "bob";
string two = "jim";
string three = one + two;
string three = String.Concat(one, two);
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 33
只要两个操作数是字符串,使用+运算符和String.Concat方法之间就没有任何区别.使用+运算符的代码实际上编译成一个String.Concat调用.
使用最符合您意图的代码.
Jon*_*eet 14
我用+的时候我知道有多少串将要连接起来-但如果你只是有一个数组?在这种情况下你不知道应用了多少次+,所以你必须调用一个方法(或者自己循环,这很糟糕).
我不记得string.Concat经常打电话- 这是一个非常罕见的.
作为guffa说,+编译分解成呼叫string.Concat反正-这是值得的注意,string实际上并不具备 A +运营商,这可能是混乱的原因,如果你曾经尝试在反射使用它!
+但有一个好处是,如果所有参数都是常量表达式,编译器将为您执行连接,因此您不需要在执行时执行此操作.在大多数代码中,这种微小的性能优势并不重要,但是当我发现最易读的代码也具有性能优势时,它总是很好的:)
我自己也有同样的问题,这个问题引发了我对它的调查,
我创建了以下类
public class Class1
{
string str = "One" + "Team";
string str2 = string.Concat("One", "Team");
}
Run Code Online (Sandbox Code Playgroud)
以下是相应的IL代码.
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 40 (0x28)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "OneTeam"
IL_0006: stfld string StringConcat.Class1::str
IL_000b: ldarg.0
IL_000c: ldstr "One"
IL_0011: ldstr "Team"
IL_0016: call string [mscorlib]System.String::Concat(string, string)
IL_001b: stfld string StringConcat.Class1::str2
IL_0020: ldarg.0
IL_0021: call instance void [mscorlib]System.Object::.ctor()
IL_0026: nop
IL_0027: ret
// end of method Class1::.ctor
}
Run Code Online (Sandbox Code Playgroud)
对我来说,它确实看起来string.Concat比重载+运算符有更多的步骤.但我确信在System.String课堂上也会发生类似的重载+操作员操作.思考?
| 归档时间: |
|
| 查看次数: |
20212 次 |
| 最近记录: |