【发布时间】:2014-07-08 03:28:43
【问题描述】:
根据文档,System.String 类型在设计上是不可变的。因此,当尝试连接字符串等时,我们只会获得对结果字符串的引用。但如果是真的,为什么这段代码在两种情况下总是返回相同的地址(当然,如果对象没有被 GC 移动):
using System;
using System.Reflection;
namespace StringImmutabilityCheck
{
class Program
{
private static unsafe void PrintAddress(string b)
{
var info = typeof(string).GetField("m_firstChar", BindingFlags.Instance | BindingFlags.NonPublic);
char value = (char)info.GetValue(b);
char* buffer = &value;
Console.WriteLine("Addres of {0} is {1}", b, (int)buffer);
}
static void Foo(ref string a)
{
a += "xxx";
}
static void Main()
{
string b = "aaaa";
PrintAddress(b);
Foo(ref b);
PrintAddress(b);
}
}
}
【问题讨论】: