public sealed class String : IComparable, ICloneable, IConvertible,
IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>
IEnumerable<char>
,這使得它可以使用 LINQ 查詢。==
操作符被重寫為比較字串的值而不是其參照。==
本來是比較參照的,但此時被重寫,這也是字串看起來像值型別的一個原因。當然,!=
操作符也會一併被重寫。
[__DynamicallyInvokable]
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
[__DynamicallyInvokable]
publie static bool operator !=(string a, string b)
{
return !string.Equals(a, b);
}
// string s = new string("1"); string s = "1"; string t = new string(new char[]{'1', '2', ' 3 ' });對應的IL程式碼如下:
IL_0000: nop
IL_0001: ldstr "1"
IL_0006: stloc.0
IL_0007: ldc.i4.3
IL_0008: newarr [mscorlib]System.Char
IL_000d: dup
IL_000e: ldtoken field valuetype '<PrivateImplementationDetails>'/'__StaticArrayInitTypeSize=6' '<PrivateImplementationDetails>'::'0D5399508427CE79556CDA71918020C1E8D15B53'
IL_0013: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,
valuetype [mscorlib]System.RuntimeFieldHandle)
IL_0018: newobj instance void [mscorlib]System.String::.ctor(char[])