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# - WCF 和 Silverlight - 二进制编码

c# - 在不创建新实例的情况下引用其他类方法

c# - Excel.Application 异常

c# - 实例与方法作为参数——理解生命周期和垃圾收集

c# - HttpClient.GetStringAsync未执行

c#语法问题-for循环和行尾

C# 如何将对象列表传递给构造函数?

c# - 在 Visual Studio 中使用 DTE 的程序包管理器控制台自动化

c# - Visual Studio - 我可以通过网络在 CE 设备上调试我的应用程序吗

javascript - Web 推送通知 'UnauthorizedRegistration' 或 'Gone' 或 'Unauthorized' - 订阅到期