MS C#字符串的实现首先检查不可变基字符串的ReferenceEquals

本文关键字:字符串 不可变 ReferenceEquals 检查 实现 MS | 更新日期: 2023-09-27 18:23:47

假设我有一些String s。

String a = "this String";
Strinb b = "this String";
String c = a;

据我所知,字符串ab不一定共享同一个不可免疫的基字符串。但是字符串ca的副本,所以它在内部指向同一个不可变字符串。

如果我比较ab是否相等,它将返回true。至少因为它们表示相同的字符序列。

如果我比较ac是否相等,它将返回true。它是检查了字符,还是先比较了指向不可变字符串的指针?


编辑:

回答我将如何检查平等:

    private void StackoverflowEquals()
    {
        String a = @"http://stackoverflow.com/questions/25932695/does-ms-c-sharp-implementation-of-string-check-referenceequals-of-the-immuteable";
        String b = @"http://stackoverflow.com/questions/25932695/does-ms-c-sharp-implementation-of-string-check-referenceequals-of-the-immuteable";
        String c = a;
        if (!(a == b)) throw new Exception();
        if (!(a == c)) throw new Exception();
    }

MS C#字符串的实现首先检查不可变基字符串的ReferenceEquals

是的。以下是equals的源代码:

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public override bool Equals(Object obj) {
            if (this == null)                        //this is necessary to guard against reverse-pinvokes and
                throw new NullReferenceException();  //other callers who do not use the callvirt instruction
            String str = obj as String;
            if (str == null)
                return false;
            if (Object.ReferenceEquals(this, obj))
                return true;
            if (this.Length != str.Length)
                return false;
            return EqualsHelper(this, str);
        }

有关完整的字符串类源代码,请参阅。