SimpleCurrency2.cs
上传用户:lxycoco
上传日期:2022-07-21
资源大小:38457k
文件大小:2k
源码类别:

C#编程

开发平台:

Others

  1. using System;
  2. namespace Wrox.ProCSharp.AdvancedCSharp
  3. {
  4.    class MainEntryPoint
  5.    {
  6.       static void Main()
  7.       {
  8.          try
  9.          {
  10.             Currency balance = new Currency(50,35);
  11.             Console.WriteLine(balance);
  12.             Console.WriteLine("balance is " + balance);
  13.             Console.WriteLine("balance is (using ToString()) " + balance.ToString());
  14.             uint balance3 = (uint) balance;
  15.             Console.WriteLine("Converting to uint gives " + balance3);
  16.             float balance2= balance;
  17.             Console.WriteLine("After converting to float, = " + balance2);
  18.             balance = (Currency) balance2;
  19.             Console.WriteLine("After converting back to Currency, = " + balance);
  20.             Console.WriteLine("Now attempt to convert out of range value of -$100.00 to a Currency:"); 
  21.             checked
  22.             {
  23.                balance = (Currency) (-50.5);
  24.                Console.WriteLine("Result is " + balance.ToString());
  25.             }
  26.          }
  27.          catch(Exception e)
  28.          {
  29.             Console.WriteLine("Exception occurred: " + e.Message);
  30.          }
  31.       }
  32.    }
  33.    struct Currency
  34.    {
  35.       public uint Dollars;
  36.       public ushort Cents;
  37.       public Currency(uint dollars, ushort cents)
  38.       {
  39.          this.Dollars = dollars;
  40.          this.Cents = cents;
  41.       }
  42.       public override string ToString()
  43.       {
  44.          return string.Format("${0}.{1,-2:00}", Dollars,Cents);
  45.       }
  46.       public static explicit operator Currency (float value)
  47.       {
  48.          checked
  49.          {
  50.             uint dollars = (uint)value;
  51.             ushort cents = (ushort)((value-dollars)*100);
  52.             return new Currency(dollars, cents);
  53.          }
  54.       }
  55.       
  56.       public static implicit operator float (Currency value)
  57.       {
  58.          return value.Dollars + (value.Cents/100.0f);
  59.       }
  60.       // DON'T DO THIS!
  61.       /*      public static implicit operator Currency (uint value)
  62.             {
  63.                return new Currency(value/100u, (ushort)(value%100));
  64.             }*/
  65.       // OK!
  66.       public static implicit operator Currency (uint value)
  67.       {
  68.          return new Currency(value, 0);
  69.       }
  70.       public static implicit operator uint (Currency value)
  71.       {
  72.          return value.Dollars;
  73.       }
  74.    }
  75. }