<分区>
Possible Duplicate:
C# String output: format or concat?
Console.WriteLine("Hi there, {0} {1}!", userName, userSurname);
Console.WriteLine("Hi there, " + userName + " " + userSurname + "!" );
我想知道这些方法有什么不同,哪种更好?
<分区>
Possible Duplicate:
C# String output: format or concat?
Console.WriteLine("Hi there, {0} {1}!", userName, userSurname);
Console.WriteLine("Hi there, " + userName + " " + userSurname + "!" );
我想知道这些方法有什么不同,哪种更好?
最佳答案
对于:
Console.WriteLine("Hi there, {0} {1}!", userName, userSurname);
您的第一个调用解析为:Console.WriteLine(string,object,object)
在伊尔
IL_000d: ldstr "Hi there, {0} {1}!"
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: call void [mscorlib]System.Console::WriteLine(string,
object,
object)
对于:
Console.WriteLine("Hi there, " + userName + " " + userSurname + "!" );
虽然您的第二条语句调用了 string.Concat
方法。
IL_0042: call string [mscorlib]System.String::Concat(string[])
IL_0047: call void [mscorlib]System.Console::WriteLine(string)
如果您使用 ILSpy 查看代码,您会看到您使用 +
进行字符串连接的部分被替换为调用 string.Concat
方法
string userName = "Test";
string userSurname = "Test2";
Console.WriteLine("Hi there, {0} {1}!", userName, userSurname);
Console.WriteLine(string.Concat(new string[]
{
"Hi there, ",
userName,
" ",
userSurname,
"!"
}));
关于性能上的差异,我相信即使有差异也可以忽略不计。
关于c# - 这些与 writeline() 中的方法有什么不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12489536/