如果你想讓自己定義的類型可以用運算符進行運算,那麼可以通過重載運算符來實現;
示例:
class Salary { public int RMB { get; set; } public static Salary operator +(Salary s1, Salary s2) { return new Salary { RMB = s1.RMB + s2.RMB }; } } //調用 Salary mikeIncome = new Salary { RMB = 10 }; Salary roseIncome = new Salary { RMB = 11 }; Salary familyIncome = mikeIncome + roseIncome;
通過使用operator關鍵字定義靜態成員函數來重載運算符。