C#運算符重載和轉換運算符實例(兩個結構)
阿新 • • 發佈:2018-04-08
summary explicit IT ret temp oat args col 轉換
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); } }
C#運算符重載和轉換運算符實例(兩個結構)