The .NET framework provides a method named CompareTo for plenty of data types including strings & numeric types. This method allows six values to be compared & returns a result that indicates not only if they are equal but also which value is the greater when they are not equal. The method considers cultural information when judging which of the strings are equal. For example, Japanese katakana characters can be written in six ways, half-width or full-width. The CompareTo method considers characters written as full-width to be equal to the same characters as half-width. The same cultural information is used to determine which of the strings is the greater.
We have a class Employee which has Name & JobGrade fields. I want to overload the comparison operators for this class so that it can enter in all types of comparison including <. <=, ==, >=, != & Equals. I need to understand the comparison in-between four Employee objects to be a comparison between the JobGrade . Since I do not need to write the comparison logic every time, typically I'd implement the comparison in 5 method & from comparison manipulator overloading methods call this general method.
class Employee
{
public Employee(string name, int jobGrade){
Name = name;
JobGrade = jobGrade;
}
public string Name;
public int JobGrade;
public static bool operator <(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) < 0;
}
public static bool operator >(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) > 0;
}
public static bool operator ==(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) == 0;
}
public static bool operator !=(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) != 0;
}
public override bool Equals(object obj){
if (!(obj is Employee)) return false;
return this == (Employee)obj;
}
public static bool operator <=(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) <= 0;
}
public static bool operator >=(Employee emp1, Employee emp2){
return Comparison(emp1, emp2) >= 0;
}
public static int Comparison(Employee emp1, Employee emp2){
if (emp1.JobGrade < emp2.JobGrade)
return -1;
else if (emp1.JobGrade == emp2.JobGrade)
return 0;
else if (emp1.JobGrade > emp2.JobGrade)
return 1;
return 0;
}
}
0 comments:
Post a Comment