10. Operator Overloading
Using the operator overload mechanism, programmers can create classes that make people feel like simple types (such as int and long. C # implements a restricted version of the C ++ operator overload, which can make such a brilliant example-the overload of the complex operator performs well.
In C #, operator = is a non-virtual (operator cannot be virtual) method of the object class, which is compared by reference. When you build a class, you can define your own = Operator. If you use your class in the collection, you should implement the IComparable interface. This interface has a CompareTo (object) method. If "this" is greater than, less than, or equal to this object, it should return positive, negative, or 0. If you want users to use your class with elegant syntax, you can select the <, <=, >=,> method. Numeric types (int, long, and so on) Implement the IComparable interface.
The following is a simple example of how to handle equals and comparison operations:
Public class Score: IComparable
{
Int value;
Public Score (int score)
{
Value = score;
}
Public static bool operator = (Score x, Score y)
{
Return x. value = y. value;
}
Public static bool operator! = (Score x, Score y)
{
Return x. value! = Y. value;
}
Public int CompareTo (object o)
{
Return value-(Score) o). value;
}
}
Score a = new Score (5 );
Score B = new Score (5 );
Object c =;
Object d = B;
Compare a and B by reference:
System. Console. WriteLine (object) a = (object) B; // The result is false.
The code of the previous sentence should be: System. Console. WriteLine (object) a = (object) B); // The result is false]
Compare the values of a and B:
System. Console. WriteLine (a = B); // The result is true.
Compare c and d by reference:
System. Console. WriteLine (c = d); // The result is false.
Compare the values of c and d:
System. Console. WriteLine (IComparable) c). CompareTo (d) = 0); // The result is true.
You can also add operators <, <=,> =, and> to the Score class. C # logical pair operators (! And must be defined together.