Jaki jest cel używania String.Concat(Object)
zamiast String.Concat(String)
w C#? Dlaczego po prostu nie użyć niejawnego wywołania zamiast podania samego Object.ToString()
, które może również spowodować boks?Cel String.Concat (Object) zamiast String.Concat (String)
Int32 i = 5;
String s = "i = ";
// Boxing happens, ToString() is called inside
Console.WriteLine(s + i);
// Why compiler doesn't call ToString() implicitly?
Console.WriteLine(s + i.ToString());
Daje nam następujące IL.
.method private hidebysig static void MyDemo() cil managed
{
// Code size 47 (0x2f)
.maxstack 2
.locals init ([0] int32 i, [1] string s)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldstr "i = "
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: box [mscorlib]System.Int32
IL_0010: call string [mscorlib]System.String::Concat(object, object)
IL_0015: call void [mscorlib]System.Console::WriteLine(string)
IL_001a: nop
IL_001b: ldloc.1
IL_001c: ldloca.s i
IL_001e: call instance string [mscorlib]System.Int32::ToString()
IL_0023: call string [mscorlib]System.String::Concat(string, string)
IL_0028: call void [mscorlib]System.Console::WriteLine(string)
IL_002d: nop
IL_002e: ret
} // end of method Program::MyDemo
Dobre pytanie. Dodałbym tutaj: dlaczego nie ma metody 'string Concat (string s, T value)', która będzie używana przez operatora '+'. –
Dennis
@Dennis, jaki byłby tego pożytek? –
@Dennis W jaki sposób kompilator konkatenuje 'T value' z' string s'? Czy jakiekolwiek 'T' może być w ogóle łączone? –