本文實例講述了C#自定義類型強制轉換的用法。分享給大家供大家參考。具體分析如下:
先來舉一個小例子
類定義:
public class MyCurrency{ public uint Dollars; public ushort Cents; public MyCurrency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() { return string.Format( "${0}.{1}", Dollars, Cents ); } //提供MyCurrency到float的隱式轉換 public static implicit operator float(MyCurrency value) { return value.Dollars + (value.Cents / 100.0f); } //把float轉換為MyCurrency,不能保證轉換肯定成功,因為float可以 //存儲負值,而MyCurrency只能存儲正數 //float存儲的數量級比uint大的多,如果float包含一個比unit大的值, //將會得到意想不到的結果,所以必須定義為顯式轉換 //float到MyCurrency的顯示轉換 public static explicit operator MyCurrency(float value) { //checked必須加在此處,加在調用函數外面是不會報錯的, //因為溢出的異常是在強制轉換運算符的代碼中發生的 //Convert.ToUInt16是為了防止丟失精度 //該段內容很重要,詳細參考"C#高級編程(中文第七版) 218頁說明" checked { uint dollars = (uint)value; ushort cents = Convert.ToUInt16((value - dollars) * 100); return new MyCurrency(dollars, cents); } }}
測試代碼:
private void btn_測試自定義類型強制轉換_Click(object sender, EventArgs e){ MyCurrency tmp = new MyCurrency(10, 20); //調用MyCurrency到float的隱式轉換 float fTmp = tmp; MessageBox.Show(fTmp.ToString()); float fTmp2 = 200.30f; //調用float到MyCurrency的顯示轉換 MyCurrency tmp2 = (MyCurrency)fTmp2; MessageBox.Show(tmp2.ToString());}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答