簡體   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