struct Celsius { private float degrees; public float Degrees { get { return this.degrees; } } public Celsius(float temp) { this.degrees = temp; Console.WriteLine("这是摄氏温度的构造!"); } public static Celsius operator +(Celsius x, Celsius y)//重载+运算符 { return new Celsius(x.degrees + y.degrees); } public static Celsius operator -(Celsius x, Celsius y)//重载-运算符 { return new Celsius(x.degrees - y.degrees); } /// <summary> /// 隐式将Celsius转换成float /// </summary> /// <param name="c">Celsius类型参数</param> /// <returns>float类型返回值</returns> public static implicit operator float(Celsius c) { return c.Degrees; } /// <summary> /// 隐式的将float转换成Celsius /// </summary> /// <param name="f">float类型参数</param> /// <returns>Celsius类型返回值</returns> public static implicit operator Celsius(float f) { Celsius c = new Celsius(f); return c; } /// <summary> /// 转换运算符,显示的将Celsius类型转换成Fahrenheit类型 /// </summary> /// <param name="c">Celsius类型参数</param> /// <returns>Fahrenheit类型返回值</returns> /// public static explicit operator Fahrenheit(Celsius c) { float fl=((9.0f / 5.0f) * c.Degrees + 32);//Celsius类型转换成Fahrenheit的规则 Fahrenheit f = new Fahrenheit(fl); return f; } public override string ToString()//重写ToString { return this.Degrees.ToString(); } } struct Fahrenheit { private float degrees; public float Degrees { get { return this.degrees; } } public Fahrenheit(float temp) { this.degrees = temp; Console.WriteLine("这是华氏温度的构造!"); } public static Fahrenheit operator +(Fahrenheit x, Fahrenheit y) { return new Fahrenheit(x.degrees + y.degrees); } public static Fahrenheit operator -(Fahrenheit x, Fahrenheit y) { return new Fahrenheit(x.degrees - y.degrees); } public static implicit operator float(Fahrenheit c) { return c.Degrees; } public static implicit operator Fahrenheit(float f) { Fahrenheit fa = new Fahrenheit(f); return fa; } public static explicit operator Celsius(Fahrenheit f) { float fl = (5.0f / 9.0f) * (f.Degrees - 32); Celsius c = new Celsius(fl); return c; } public override string ToString() { return this.Degrees.ToString(); } } class Program { static void Main(string[] args) { Fahrenheit f = new Fahrenheit(100f); Console.WriteLine("{0} fahrenheit = {1} celsius", f.Degrees, (Celsius)f); Celsius c = 32f;//隐式将float转换成celsius Console.WriteLine("{0} celsius = {1} fahrenheit",c.Degrees,(Fahrenheit)c); Fahrenheit f2 = f + (Fahrenheit)c;//验证Fahrenheit的+重载 Console.WriteLine("{0} + {1} = {2} fahernheit",f.Degrees,(Fahrenheit)c,f2.Degrees); Fahrenheit f3 = 100f;//隐式将float转换成Fahrenheit Console.WriteLine("{0} fahrenheit",f3.Degrees); } }