对不起,我不太善于解释问题.我可以通过以下示例更好地解释我的问题:
string first = "hello";
string second = "Bye";
first = second;
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,考虑第三行first=second.
在这里,我将对象排在第二位.因为c#中的字符串是不可变的,即每次为现有字符串对象分配新值时,都会创建一个新对象,CLR将释放旧对象.(我从这里读到这个1).所以简单地说它意味着first第一行中的对象first与第三行中的对象不同.
所以我的问题是我怎样才能证明两者有所不同?
即如果它(字符串)在C中是可能的,那么我可以在第三个语句之前和之后打印两个对象的地址来证明它.
是否有任何方法可以访问那里的地址或其他替代方案?
如果您想查看内存中的物理位置,可以使用以下(不安全)代码.
private static void Main(string[] args)
{
unsafe
{
string first = "hello";
fixed (char* p = first)
{
Console.WriteLine("Address of first: {0}", ((int)p).ToString());
}
string second = "Bye";
fixed (char* p = second)
{
Console.WriteLine("Address of second: {0}", ((int)p).ToString());
}
first = second;
fixed (char* p = first)
{
Console.WriteLine("Address of first: {0}", ((int)p).ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我机器上的示例输出:
Address of first: 41793976
Address of second: 41794056
Address of first: 41794056
Run Code Online (Sandbox Code Playgroud)
你会注意到,.NET缓存了完全有效的字符串实例,因为它们是不可变的.要演示此行为,您可以更改second为hello并且所有内存地址都相同.这就是为什么你不应该依赖本机内存并只使用托管方式处理对象.
也可以看看:
公共语言运行库通过维护一个名为intern pool的表来保存字符串存储,该表包含对在程序中以编程方式声明或创建的每个唯一文字字符串的单个引用.因此,具有特定值的文字字符串实例仅在系统中存在一次.
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |