欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#自定義類型強制轉(zhuǎn)換實例分析

 更新時間:2015年05月16日 11:43:58   作者:永遠愛好寫程序  
這篇文章主要介紹了C#自定義類型強制轉(zhuǎn)換的方法,實例分析了C#類型轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下

本文實例講述了C#自定義類型強制轉(zhuǎn)換的用法。分享給大家供大家參考。具體分析如下:

先來舉一個小例子

類定義:

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)換肯定成功,因為float可以
  //存儲負值,而MyCurrency只能存儲正數(shù)
  //float存儲的數(shù)量級比uint大的多,如果float包含一個比unit大的值,
  //將會得到意想不到的結(jié)果,所以必須定義為顯式轉(zhuǎn)換
  //float到MyCurrency的顯示轉(zhuǎn)換
  public static explicit operator MyCurrency(float value)
  {
    //checked必須加在此處,加在調(diào)用函數(shù)外面是不會報錯的,
    //因為溢出的異常是在強制轉(zhuǎn)換運算符的代碼中發(fā)生的
    //Convert.ToUInt16是為了防止丟失精度
    //該段內(nèi)容很重要,詳細參考"C#高級編程(中文第七版) 218頁說明"
    checked
    {
      uint dollars = (uint)value;
      ushort cents = Convert.ToUInt16((value - dollars) * 100);
      return new MyCurrency(dollars, cents);
    }
  }
}

測試代碼:

private void btn_測試自定義類型強制轉(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());
}

希望本文所述對大家的C#程序設(shè)計有所幫助。

相關(guān)文章

最新評論