operator 可以用于重载运算符和自定义类型转换
实例
public class _20210302_1_Model { public string Name { get; set; } public int Age { get; set; } /* * operator 用于重载运算符 */ // 重载运算符"+" public static int operator + (_20210302_1_Model m1, _20210302_1_Model m2) { return m1.Age + m2.Age; } // 重载运算符"-" public static int operator -(_20210302_1_Model m1, _20210302_1_Model m2) { return m1.Age - m2.Age; } /* * operator 用于自定义类型转换 */ // 定义隐式的从_20210302_1_Model到int的类型转换 public static implicit operator int (_20210302_1_Model m1) { return m1.Age; } // 定义显式的从_20210302_1_Model到string的类型转换 public static explicit operator string(_20210302_1_Model m1) { return m1.Name; } }
测试代码
_20210302_1_Model m1 = new _20210302_1_Model { Name = "M1", Age = 10 }; _20210302_1_Model m2 = new _20210302_1_Model { Name = "M2", Age = 20 }; var res1 = m1 + m2; // 30 var res2 = m2 - m1; // 10 int res3 = m1; // 隐式转换,转换结果 10 string res4 = (string)m2; // 显示转换,转换结果 "M2"