字符串连接及$
一、+号
常见的用string的+用于字符连接时:
using System;
namespace 输出打印方式
{
class Program
{
static void Main(string[] args)
{
int age = 18;
string Prefix = "\"dp\" is ";
string test1 = Prefix + age;
Console.WriteLine(test1);
Console.ReadKey();
}
}
}
扩展:String加号的重载?
首先查看一下String类:
其中只有关于(!=和==)的重载如下并无+的重载。
namespace System
{
[ComVisible(true)]
[DefaultMember("Chars")]
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<String>, IEnumerable<char>, IEnumerable, IEquatable<String>
{
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator ==(String a, String b);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator !=(String a, String b);
}
通过ILDASM工具转换成中间代码:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 37 (0x25)
.maxstack 2
.locals init ([0] int32 age,
[1] string Prefix,
[2] string test1)
IL_0000: nop
IL_0001: ldc.i4.s 18
IL_0003: stloc.0
IL_0004: ldstr "\"dp\" is "
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: ldloc.0
IL_000c: box [mscorlib]System.Int32
IL_0011: call string [mscorlib]System.String::Concat(object, //关键语句
object)
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: call void [mscorlib]System.Console::WriteLine(string)
IL_001d: nop
IL_001e: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
IL_0023: pop
IL_0024: ret
} // end of method Program::Main
可以看见,默认的直接就把String的+转换成的String.Concat函数来执行。
二、String.Format
代码如下:
using System;
namespace 输出打印方式
{
class Program
{
static void Main(string[] args)
{
int age = 18;
string Prefix = "\"dp\" is ";
string test2 = string.Format("{0}{1}",Prefix,age);
Console.WriteLine(test2);
Console.ReadKey();
}
}
}
三、$号
代码如下:
using System;
namespace 输出打印方式
{
class Program
{
static void Main(string[] args)
{
int age = 18;
string Prefix = "\"dp\" is ";
string test3 = $"{Prefix}{age}";
Console.WriteLine(test3);
Console.ReadKey();
}
}
}
再来看一下IL转的中间代码:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 42 (0x2a)
.maxstack 3
.locals init ([0] int32 age,
[1] string Prefix,
[2] string test3)
IL_0000: nop
IL_0001: ldc.i4.s 18
IL_0003: stloc.0
IL_0004: ldstr "\"dp\" is "
IL_0009: stloc.1
IL_000a: ldstr "{0}{1}"
IL_000f: ldloc.1
IL_0010: ldloc.0
IL_0011: box [mscorlib]System.Int32
IL_0016: call string [mscorlib]System.String::Format(string,//关键代码
object,
object)
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: call void [mscorlib]System.Console::WriteLine(string)
IL_0022: nop
IL_0023: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
IL_0028: pop
IL_0029: ret
} // end of method Program::Main
也可以轻易发现,$起始也是默认转换成的Format的形式进行连接的。
四、运行结果
一切皆从真实心中作。