繁体   English   中英

当指定类型的运算符重载存在时,C#编译器如何确定泛型方法中的引用相等性?

[英]How does C# compiler determine reference equality in generic methods when operator overloads for a specified type exists?

目前正在研究乔恩·斯基特(Jon Skeet)的“ C#In Depth,第3版”,我对引用相等有一个小问题。 对于感兴趣的人,以下代码是Chptr 3 p.80的Jon代码的很小变化:

公共功能存储在一个类中; 请注意,“ T”仅限于引用类型:

    public static bool AreReferencesEqual<T>(T i1, T i2) where T : class
    {
        return i1 == i2;
    }

驱动方式:

    static void Main(string[] args)
    {
        string name = "Joe";
        string one = "one" + name;
        string two = "one" + name;
        // test one (uses string operator== overload, and returns true)
        Console.WriteLine(one == two);

        // test two (according to Jon, when the compiler compiles the generic method,
        // it has no idea what overloads will be provided, and therefore treats
        // the == comparison with respect to the more general 'object' type.
        // Therefore this method should return false because, of course, the value
        // of the references 'one' and 'two' are not the same.
        Console.WriteLine(ReferenceEquality.AreReferencesEqual(one, two));
    }

与Jon的解释一致,运行该驱动程序文件时,输出为“ True”,“ False”。 现在,我以为我完全理解了这一点,但是当我将驱动程序文件更改为此时,我感到很惊讶:

    static void Main(string[] args)
    {
        string one = "one";
        string two = "one";
        Console.WriteLine(one == two);
        Console.WriteLine(ReferenceEquality.AreReferencesEqual(one, two));
    }

并在输出上看到“ True”,“ True”。 这背后的原因是什么? 现在是使用字符串operator ==重载的通用方法,还是由于我不知道的某些微妙的编译器技术,引用确实相等吗? 还是我完全错过了船,误解了乔恩的解释?

感谢您抽出宝贵的时间阅读和回复。

它们是引用等效的,因为常量匹配,因此编译器使用相同的基础字符串。 字符串(在幕后)在C#中是不可变的-当您将字符串添加在一起时,会生成一个新的字符串实例-在第二个代码集中永远不会发生,因此,它们实际上都引用RAM中相同的字节块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM