Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Переопределение Equals

Поскольку Equals является виртуальным методом, любой класс может переопределить его реализацию. Любой класс, представляющий значение (в принципе, любой тип значения) или набор значений в качестве группы, такой как класс сложных чисел, должен переопределять Equals. Если тип реализует IComparable, он должен переопределять Equals.

Новая реализация Equals должна соответствовать всем гарантиям Equals:

  • x.Equals(x) возвращает true.

  • x.Equals (y) возвращает то же значение, что и y.Equals (x).

  • если (x.Equals (y) && y.Equals (z)) возвращает true, то x.Equals (z) возвращает true.

  • Последовательные вызовы x.Equals (y) возвращают то же значение до тех пор, пока объекты, на которые ссылается x и y, не будут изменены.

  • x.Equals (ноль) возвращает false (только для не нулевых типов значений).

The new implementation of Equals should not throw exceptions. It is recommended that any class that overrides Equals also override Object..::.GetHashCode. It is also recommended that in addition to implementing Equals (object), any class also implement Equals (type) for their own type, to enhance performance. For example:

class TwoDPoint : System.Object

{

public readonly int x, y;

public TwoDPoint(int x, int y) //constructor

{

this.x = x;

this.y = y;

}

public override bool Equals(System.Object obj)

{

// If parameter is null return false.

if (obj == null)

{

return false;

}

// If parameter cannot be cast to Point return false.

TwoDPoint p = obj as TwoDPoint;

if ((System.Object)p == null)

{

return false;

}

// Return true if the fields match:

return (x == p.x) && (y == p.y);

}

public bool Equals(TwoDPoint p)

{

// If parameter is null return false:

if ((object)p == null)

{

return false;

}

// Return true if the fields match:

return (x == p.x) && (y == p.y);

}

public override int GetHashCode()

{

return x ^ y;

}

}

Новая реализация Equals не должна создавать исключения. Рекомендуется, чтобы любой класс, переопределяющий Equals, также переопределял Object..::.GetHashCode. Также рекомендуется, чтобы помимо реализации Equals (объект), любой класс также реализовывал Equals (тип) для собственных типов с целью повышения производительности. Пример.

---

Any derived class that can call Equals on the base class should do so before finishing its comparison. In the following example, Equals calls the base class Equals, which checks for a null parameter and compares the type of the parameter with the type of the derived class. That leaves the implementation of Equals on the derived class the task of checking the new data field declared on the derived class:

class ThreeDPoint : TwoDPoint

{

public readonly int z;

public ThreeDPoint(int x, int y, int z)

: base(x, y)

{

this.z = z;

}

public override bool Equals(System.Object obj)

{

// If parameter cannot be cast to ThreeDPoint return false:

ThreeDPoint p = obj as ThreeDPoint;

if ((object)p == null)

{

return false;

}

// Return true if the fields match:

return base.Equals(obj) && z == p.z;

}

public bool Equals(ThreeDPoint p)

{

// Return true if the fields match:

return base.Equals((TwoDPoint)p) && z == p.z;

}

public override int GetHashCode()

{

return base.GetHashCode() ^ z;

}

}

Любой производный класс, который может вызвать Equals в базовом классе, должен вызывать этот метод до завершения сравнения. В следующем примере Equals вызывает базовый класс Equals, который проверяет нулевой параметр и сравнивает тип параметра с типом производного класса. На реализацию Equals в производном классе это накладывает задачу проверки новых полей данных, объявленных в производном классе:

---

Overriding Operator ==

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

Overloaded operator == implementations should not throw exceptions. Any type that overloads operator == should also overload operator !=. For example:

//add this code to class ThreeDPoint as defined previously

//

public static bool operator ==(ThreeDPoint a, ThreeDPoint b)

{

// If both are null, or both are same instance, return true.

if (System.Object.ReferenceEquals(a, b))

{

return true;

}

// If one is null, but not both, return false.

if (((object)a == null) || ((object)b == null))

{

return false;

}

// Return true if the fields match:

return a.x == b.x && a.y == b.y && a.z == b.z;

}

public static bool operator !=(ThreeDPoint a, ThreeDPoint b)

{

return !(a == b);

}

Note:

A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead creates a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.

Перегрузка оператора равенства (==)

По умолчанию оператор == проверяет равенство ссылок, определяя, указывают ли две ссылки на один и тот же объект. Таким образом, ссылочные типы не должны реализовывать оператор ==, чтобы получить эту функцию. Если тип является неизменяемым, то есть, если содержащиеся в экземпляре данные нельзя изменять, перегрузка оператора == для сравнения равенства значений вместо равенства ссылок может иметь смысл, поскольку как неизменяемые объекты, они могут считаться таковыми до тех пор, пока будут иметь одинаковые значения. Не рекомендуется переопределять оператор == в типах, не являющихся неизменяемыми.

Реализация перегруженного оператора == не должна приводить к исключениям. Любой тип, перегружающий оператор ==, также должен перегружать оператор !=. Пример.

---

Примечание.

Распространенной ошибкой при перегрузке оператора == является использование (a == b), (a == null) или (b == null) для проверки равенства ссылок. Вместо нужного результата, это создает вызов перегруженного оператора ==, приводя к бесконечному циклу. Чтобы избежать цикла, используйте ReferenceEquals или приведите тип к Object.

Objects, Classes and Structs

C# is an object-oriented programming language and uses classes and structs to implement types such as Windows Forms, user interface controls, and data structures. A typical C# application consists of classes defined by the programmer, combined with classes from the .NET Framework.

C# provides many powerful ways of defining classes, such as providing different access levels, inheriting features from other classes, and enabling the programmer to specify what occurs when types are instantiated or destroyed.

Classes can also be defined as generic by using type parameters that enable client code to customize the class in a type-safe and efficient manner. A single generic class, for example System.Collections.Generic..::.List<(Of <(T>)>) in the .NET Framework can be used by client code to store integers, strings, or any other type of object.

Overview

Objects, classes, and structs have the following properties:

  • Objects are instances of a given data type. The data type provides a blueprint for the object that is created, or instantiated, when the application is executed.

  • New data types are defined by using classes and structs.

  • Classes and structs form the building blocks of C# applications that contain code and data. A C# application will always contain of at least one class.

  • A struct can be considered a lightweight class, ideal for creating data types that store small amounts of data, and does not represent a type that might later be extended through inheritance.

  • C# classes support inheritance; classes can derive from a previously defined class.