本文實(shí)例講述了C#自定義類型強(qiáng)制轉(zhuǎn)換的用法。分享給大家供大家參考。具體分析如下:
先來舉一個(gè)小例子
類定義:
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的隱式轉(zhuǎn)換  public static implicit operator float(MyCurrency value)  {    return value.Dollars + (value.Cents / 100.0f);  }  //把float轉(zhuǎn)換為MyCurrency,不能保證轉(zhuǎn)換肯定成功,因?yàn)閒loat可以  //存儲(chǔ)負(fù)值,而MyCurrency只能存儲(chǔ)正數(shù)  //float存儲(chǔ)的數(shù)量級(jí)比uint大的多,如果float包含一個(gè)比unit大的值,  //將會(huì)得到意想不到的結(jié)果,所以必須定義為顯式轉(zhuǎn)換  //float到MyCurrency的顯示轉(zhuǎn)換  public static explicit operator MyCurrency(float value)  {    //checked必須加在此處,加在調(diào)用函數(shù)外面是不會(huì)報(bào)錯(cuò)的,    //因?yàn)橐绯龅漠惓J窃趶?qiáng)制轉(zhuǎn)換運(yùn)算符的代碼中發(fā)生的    //Convert.ToUInt16是為了防止丟失精度    //該段內(nèi)容很重要,詳細(xì)參考"C#高級(jí)編程(中文第七版) 218頁說明"    checked    {      uint dollars = (uint)value;      ushort cents = Convert.ToUInt16((value - dollars) * 100);      return new MyCurrency(dollars, cents);    }  }}測試代碼:
private void btn_測試自定義類型強(qiáng)制轉(zhuǎn)換_Click(object sender, EventArgs e){  MyCurrency tmp = new MyCurrency(10, 20);  //調(diào)用MyCurrency到float的隱式轉(zhuǎn)換  float fTmp = tmp;  MessageBox.Show(fTmp.ToString());  float fTmp2 = 200.30f;  //調(diào)用float到MyCurrency的顯示轉(zhuǎn)換  MyCurrency tmp2 = (MyCurrency)fTmp2;  MessageBox.Show(tmp2.ToString());}希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
| 
 
 | 
新聞熱點(diǎn)
疑難解答
圖片精選