为什么两个单独的字符串引用相等?换句话说,为什么s和t都是相同的引用? [英] Why are 2 separate string references equal? In other words why are s and t both the same reference?

查看:154
本文介绍了为什么两个单独的字符串引用相等?换句话说,为什么s和t都是相同的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么两个字符串引用相同?我正在尝试编写一个复制构造函数,并希望避免指向同一字符串的字符串引用。

Why are the 2 string references the same? I am trying to write a copy constructor and want to avoid string references that point to the same string.

using System;

namespace StringRefTest
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("String Test!");

            string s = "f"; // This should be one reference
            string t = "f"; // This should be another

            if (ReferenceEquals(s, t))
                Console.WriteLine("Ref Same"); 
            else
                Console.WriteLine("Ref Not Same"); // Should be true

            // The references are the same

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}


推荐答案

与其他人所说的相反,此行为不是由于字符串interning。编译后的程序集的元数据包含一个使用的字符串常量表。 C#编译器足够聪明,可以注意到这两个字符串相同,并且对两个字符串使用相同的常量。如果编译器没有注意到这一点,那么字符串interning就是与众不同的原因。

Contrary to what others said, this behavior is not due to string interning. The compiled assembly's metadata contain a table of string constants used. And the C# compiler is smart enough to notice those two strings are the same and use the same constant for both. If the compiler didn't notice this, string interning would be what makes the difference.

为了证明这一点,我尝试运行带有和不带有interning的简单程序。根据通过C#的 CLR,您可以在程序集上指定 [CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] 属性,以建议关闭字符串内联。 C#编译器总是发出此属性,但是CLR v.4.0仅在使用ngen时才接受该属性。这对我们很方便:

To demonstrate this, I tried running a simple program with and without interning. According to CLR via C#, you can specify the [CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] attribute on an assembly to suggest turning off string inlining. The C# compiler always emits this attribute, but the CLR v.4.0 honors it only when using ngen. This comes in handy for us:

>interning.exe
s and t are reference equal: True
s is interned: True
t is interned: True

>ngen install interning.exe
Microsoft (R) CLR Native Image Generator - Version 4.0.30319.17020
Copyright (c) Microsoft Corporation.  All rights reserved.
1>    Compiling assembly C:\Users\Svick\AppData\Local\Temporary Projects\interni
ng\bin\Debug\interning.exe (CLR v4.0.30319) ...

>interning.exe
s and t are reference equal: True
s is interned: False
t is interned: False

这证明对于具有相同值的两个字符串常量,引用相等时不需要字符串插入。

This proves that string interning is not required for two string constants with the same value to be reference equal.

这篇关于为什么两个单独的字符串引用相等?换句话说,为什么s和t都是相同的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆