c# - 我如何区分 C# 中的两个相同对象?

标签 c#

不好意思,我不太会解释问题。 我可以通过以下示例更好地解释我的问题:

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/

相关文章:

c# - 对于添加到队列的新消息,MSMQ 上是否有任何事件或回调

c# - Json 架构日期验证

c# - 丢失在 Global.asax 中声明并在 webrole 的 onstart 事件中初始化的静态变量的值

c# - WPF 用户控件双向绑定(bind)依赖属性

c# - 如何在 C# 中将整数值转换为二进制值作为字符串?

c# - 防止 Windows 窗体 datagridview 在单元格编辑后更改行

c# - 在 C# 中使用反射获取具有单个属性或没有属性的方法

c# - ASP.NET Identity framework (forms) 如何使用 bootstrap

c# - 异常处理

c# - 如何为WPF View 模型和数据模型类选择命名约定?