c# - 为什么实习生对字符串的副本不起作用?

标签 c#

给定:

        object literal1 = "abc";
        object literal2 = "abc";

        object copiedVariable = string.Copy((string)literal1);

        if (literal1 == literal2)
            Console.WriteLine("objects are equal because of interning");//Are equal

        if(literal1 == copiedVariable)
            Console.WriteLine("copy is equal");
        else
            Console.WriteLine("copy not eq");//NOT equal

这些结果表明 copiedVariable 不受字符串驻留的影响。为什么?

在某些情况下,具有未驻留的等效字符串是否有用,或者这种行为是由于某些语言细节引起的吗?

最佳答案

如果您考虑一下,字符串的驻留是它在编译时对文字触发的过程。这意味着:

  • 当您将文字分配/绑定(bind)到变量时,它是隐式的
  • 当你复制一个引用时它是隐含的(即字符串 a = some_other_string_variable;)

另一方面,如果您手动创建字符串的实例 - 在运行时使用 StringBuilder 或通过复制,那么您必须专门请求通过调用 Intern String 类的方法。

即使在文档的备注部分中也指出:

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. For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

以及 Copy 的文档String 类的方法声明它:

Creates a new instance of String with the same value as a specified String.

这意味着它不会只返回对同一字符串的引用(来自实习生池)。再说一次,如果确实如此,那么它就没有多大用处了,不是吗?!

关于c# - 为什么实习生对字符串的副本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161225/

相关文章:

c# - 当构造函数抛出异常时确保定义明确的对象状态

c# - 有没有办法跨多行跨越长方法名称?

c# - 带有 .NET Framework 4.0 的 Windows XP SP3 上的 .NET Framework 3.0 应用程序

c# - 什么是 C++ std::pair 的 C# 模拟?

c# - 仅使用服务证书的 WCF 消息安全性

c# - 获取所有值的枚举扩展方法

c# - Blazor(客户端)StateHasChanged() 不更新页面

c# - Microsoft Enterprise Library 缓存应用程序 block 不是线程安全的?

c# - 使用带有特殊字符的正则表达式分割字符串

c# - 为什么在 GetHashCode 实现中使用初始素数?