Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'c# bible 2002 phần 4', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Unary minus Logical negation Bitwise complement operator Prefix increment Prefix decrement The true keyword The false keyword Overloading unary plus If you need to overload the unary plus unary minus negation or bitwise complement operators in your class or structure define a method with the following characteristics A return type of your choice The keyword operator The operator being overloaded A parameter list specifying a single parameter of the type of class or structure containing the overloaded operator method As an example revisit the Point class from Chapter 9. Suppose that you want to add a unary plus operator to the class that when used ensures that the coordinates of the point are both positive. This is implemented in Listing 10-1. Listing 10-1 Overloading the Unary Plus Operator class Point public int X public int Y public static Point operator Point RValue Point NewPoint new Point if RValue.X 0 NewPoint.X - RValue.X else NewPoint.X RValue.X if RValue.Y 0 NewPoint.Y - RValue.Y else NewPoint.Y RValue.Y return NewPoint public static void Main Point MyPoint new Point MyPoint.X -100 MyPoint.Y 200 System.Console.WriteLine MyPoint.X System.Console.WriteLine MyPoint.Y MyPoint MyPoint System.Console.WriteLine MyPoint.X System.Console.WriteLine MyPoint.Y The Main method creates an object of type Point and sets its initial coordinates to 100 200 . It then applies the unary plus operator to the object and reassigns the result to the same point. It prints out the x and y coordinates to the console. The output of Listing 10-1 is shown in Figure 10-1. Figure 10-1 Overloading the unary operator The coordinates of the point have changed from -100 200 to 100 200 . The overloaded operator code is executed when the following statement is reached MyPoint MyPoint When this statement is reached the unary plus operator overload for the Point class is executed. The expression on the right side of the equal sign is supplied as the parameter to the method. Note The expression .