Есть класс State, который представляет государство:
class State { public decimal Population { get; set; } // население public decimal Area { get; set; } // территория }
Добавьте в класс оператор сложения, который бы позволял объединять государства. А также операторы сравнения < и > для сравнения государств по какому-нибудь критерию (например, по населению или территории). Наподобие
State state1 = new State(); State state2 = new State(); State state3 = state1 + state2; bool isGreater = state1 > state2;
Возможная реализация:
class State { public decimal Population { get; set; } // население public decimal Area { get; set; } // территория public static State operator +(State s1, State s2) { return new State { Population = s1.Population + s2.Population, Area = s1.Area + s2.Area }; } public static bool operator >(State s1, State s2) { return s1.Area > s2.Area; } public static bool operator <(State s1, State s2) { return s1.Area < s2.Area; } }
Применение:
State aragon = new State { Area = 23, Population = 2 }; State kastilia = new State { Area = 41, Population = 5 }; State spain = aragon + kastilia; Console.WriteLine(spain.Population); // 7 if(aragon > kastilia) { Console.WriteLine("Арагон больше Кастилии"); } else { Console.WriteLine("Арагон меньше Кастилии"); }
Как известно, неотъемлемыми компонентами бутерброда являются хлеб и масло. Допустим, у нас есть следующие классы:
// хлеб class Bread { public int Weight { get; set; } // масса } // масло class Butter { public int Weight { get; set; } // масса } // бутерброт class Sandwich { public int Weight { get; set; } // масса }
Добавьте в один из классов оператор сложения, чтобы при объединении хлеба и масла получался бутерброд, и, тем самым, компилировался и выполнялся без ошибок следующий код:
Bread bread = new Bread { Weight = 80 }; Butter butter = new Butter { Weight = 20 }; Sandwich sandwich = bread + butter; Console.WriteLine(sandwich.Weight); // 100
Возможная реализация:
// хлеб class Bread { public int Weight { get; set; } // масса public static Sandwich operator +(Bread bread, Butter butter) { return new Sandwich { Weight = bread.Weight + butter.Weight }; } } // масло class Butter { public int Weight { get; set; } // масса } // бутерброт class Sandwich { public int Weight { get; set; } // масса }