不好意思,我不太会解释问题。 我可以通过以下示例更好地解释我的问题:
string first = "hello";
string second = "Bye";
first = second;
在上面的例子中,考虑第三行 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());
}
}
}
我机器上的示例输出:
Address of first: 41793976
Address of second: 41794056
Address of first: 41794056
您会注意到,.NET 缓存了完全有效的字符串实例,因为它们是不可变的。要演示此行为,您可以将 second
更改为 hello
,所有内存地址都将相同。这就是为什么您不应该依赖 native 内存的东西而只使用托管方式来处理对象。
另见:
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
Source: String.Intern (MSDN)
关于c# - 我如何区分 C# 中的两个相同对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19354731/