SimpleCurrency.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.             float balance2= balance;
  15.             Console.WriteLine("After converting to float, = " + balance2);
  16.             balance = (Currency) balance2;
  17.             Console.WriteLine("After converting back to Currency, = " + balance);
  18.             Console.WriteLine(
  19.                "Now attempt to convert out of range value of -$100.00 to a Currency:"); 
  20.             checked
  21.             {
  22.                balance = (Currency) (-50.5);
  23.                Console.WriteLine("Result is " + balance.ToString());
  24.             }
  25.          }
  26.          catch(Exception e)
  27.          {
  28.             Console.WriteLine("Exception occurred: " + e.Message);
  29.          }
  30.       }
  31.    }
  32.    struct Currency
  33.    {
  34.       public uint Dollars;
  35.       public ushort Cents;
  36.       public Currency(uint dollars, ushort cents)
  37.       {
  38.          this.Dollars = dollars;
  39.          this.Cents = cents;
  40.       }
  41.       public override string ToString()
  42.       {
  43.          return string.Format("${0}.{1,-2:00}", Dollars,Cents);
  44.       }
  45.       public static explicit operator Currency (float value)
  46.       {
  47.          uint dollars = (uint)value;
  48.          ushort cents = (ushort)((value-dollars)*100);
  49.          return new Currency(dollars, cents);
  50.       }
  51.       
  52.       public static implicit operator float (Currency value)
  53.       {
  54.          return value.Dollars + (value.Cents/100.0f);
  55.       }
  56.    }
  57. }