您好,登錄后才能下訂單哦!
----------------------------------------------------------------------Currency.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { //類和結構相似 public struct Currency { private uint dollars; //元 private ushort cents; //分 public Currency(uint i, ushort s)//初始化構造函數 { this.dollars = i; this.cents = s; } public override string ToString() { return string.Format("{0}.{1,2:00}", dollars, cents); } //看情況選擇是顯示裝換還是隱式轉換,(uint和ushort都可以隱式轉換為float) //重載運算符必須使用public static //implicit 隱式轉換 //把Currency對象隱式轉換為float類型 public static implicit operator float(Currency c) { return c.dollars + c.cents / 100.0f; } //explicit為顯式轉換 //把float對象顯式轉換為Currency類型 public static explicit operator Currency(float f) { checked//溢出則拋出異常 { uint i = (uint)f; ushort s = Convert.ToUInt16((f - i) * 100); return new Currency(i, s); } } } }
----------------------------------------------------------------------主程序
Currency c = new Currency(50, 35); float f = (float)(c); c = (Currency)f; Console.WriteLine(c.ToString()); Console.ReadKey();
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。