下面这段代码:
string a="hello";
string b=string.Copy(a);
string c="hello";
Console.WriteLine((object)a==(object)b);
console.Writeline((object)a==(object)c);
输出是:
false
true
为什么是这个结果?
string a="hello";
string b=string.Copy(a);
string c="hello";
Console.WriteLine((object)a==(object)b);
console.Writeline((object)a==(object)c);
输出是:
false
true
为什么是这个结果?
object a="hello";
object c="hello";
Console.WriteLine(a==c);结果true
ldstr "hello"
stloc.0
object c="hello";则对应以下il代码:
ldstr "hello"
stloc.1
可以看到决定因素在于ldstr "hello"。
以下是msdn对ldstr的描述:ldstr 指令推送对表示在元数据中存储的特定字符串的新字符串对象的对象引用(O 类型)。ldstr 指令分配必需的内存量并执行将字符串从在文件中使用的形式转换为在运行时要求的字符串格式所需的任何格式转换。公共语言结构 (CLI) 保证两个 ldstr 指令(这两个指令引用具有相同字符序列的两个元数据标记)的结果返回完全相同的字符串对象(称作“字符串限定”的进程)。