Defining Operator Pairs

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:2

lượt xem

Defining Operator Pairs

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Xác định cặp Một số nhà khai thác vận hành tự nhiên đi theo cặp. Ví dụ, nếu bạn có thể so sánh hai giờ giá trị bằng cách sử dụng = điều hành!, Bạn sẽ mong đợi để có thể so sánh hai giờ cũng giá trị bằng cách sử dụng toán tử ==

Chủ đề:

Nội dung Text: Defining Operator Pairs

  1. Defining Operator Pairs Some operators naturally come in pairs. For example, if you can compare two Hour values by using the != operator, you would expect to be able to also compare two Hour values by using the == operator. The C# compiler enforces this very reasonable expectation by insisting that if you define either operator== or operator!=, you must define them both. This neither-or-both rule also applies to the < and > operators and the = operators. The C# compiler does not write any of these operator partners for you. You must write them all explicitly yourself, regardless of how obvious they might seem. Here are the == and != operators for the Hour struct: struct Hour { public Hour(int initialValue) { this.value = initialValue; } ... public static bool operator==(Hour lhs, Hour rhs) { return lhs.value == rhs.value; } public static bool operator!=(Hour lhs, Hour rhs) { return lhs.value != rhs.value; } ... private int value; } The return type from these operators does not actually have to be Boolean. However, you would have to have a very good reason for using some other type or these operators could become very confusing! NOTE If you define operator== and operator!=, you should also override the Equals and GetHashCode methods inherited from System.Object. The Equals method should exhibit exactly the same behavior as operator== (define one in terms of the other). The GetHashCode method is used by other classes in the .NET Framework. (When you use an object as a key in a hash table for example, the GetHashCode method is called on the
  2. object to help calculate a hash value. For more information, see the .NET Framework Reference documentation supplied with Visual Studio 2005). All this method needs to do is return a distinguishing integer value (don't return the same integer from the GetHashCode method of all your objects though as this will reduce the effectiveness of the hashing algorithms).
Đồng bộ tài khoản