List operator == In the C# Language Specification Version 4

前端 未结 2 2011
萌比男神i
萌比男神i 2020-12-20 11:33

In the C# Language Specification Version 4, 1.6.7.5 Operators is information about List operators: == and !=. But I can\'t fi

相关标签:
2条回答
  • 2020-12-20 11:51

    The spec is indeed correct, although confusing. The spec defines a class called List (poor naming choice).

    The following table shows a generic class called List, which implements a growable list of objects. The class contains several examples of the most common kinds of function members.

    This class can be seen in the spec at section 1.6.7. The Equals operator is overloaded and matches the output explained above. Perhaps a better name should have been chosen for that class.

    static bool Equals(List<T> a, List<T> b) {
        if (a == null) return b == null;
        if (b == null || a.count != b.count) return false;
        for (int i = 0; i < a.count; i++) {
            if (!object.Equals(a.items[i], b.items[i])) {
                return false;
            }
        }
      return true;
    }
    
    0 讨论(0)
  • 2020-12-20 11:54

    List<T> is a reference type which does not overload operator==. Therefore, it uses the default reference equality semantics. You seem to be under the impression that it overrides operator== to provide value semantics, but it does not. a will equal b when a and b both refer to the same List<T> instance.

    EDIT: So I looked at the spec myself. It says:

    The List class declares two operators, operator == and operator !=, and thus gives new meaning to expressions that apply those operators to List instances. Specifically, the operators define equality of two List instances as comparing each of the contained objects using their Equals methods. The following example uses the == operator to compare two List instances.

    Honestly... I have no clue what they're talking about, but this does not appear to be correct. As far as I can tell after running a few tests the List<T> class uses reference equality. Good question.

    EDIT2: Decompiled List<T>, no operator== and/or operator!= overload. The spec appears to be completely incorrect in this case.

    0 讨论(0)
提交回复
热议问题