//1、重载内置运算符
public class Salary {
public int RMB { get; set; }
public static Salary operator +(Salary s1, Salary s2) {
s2.RMB += s1.RMB;
return s2;
}
}
public class Test {
public static void Main(string[] args) {
var a = new Salary() { RMB = 1 };
var b = new Salary() { RMB = 3 };
var c = a + b;
}
}
//2、隐式转换
public class Salary {
public int RMB { get; set; }
public static implicit operator Salary(string rmb) {
return new Salary() { RMB = int.Parse(rmb) };
}
}
public class Test {
public static void Main(string[] args) {
var a = (Salary)"1";//正确
Salary b = "2"; //正确
var c = a + b;
}
}
//3、显式转换(定义之后只能强制转换)
public class Salary {
public int RMB { get; set; }
public static explicit operator Salary(string rmb) {
return new Salary() { RMB = int.Parse(rmb) };
}
}
public class Test {
public static void Main(string[] args) {
var a = (Salary)"1";//正确
Salary b = "2"; //报错
var c = a + b;
}
}