namespace CurrencyTest
{
struct Currency
{
public uint Dollars;
public ushort Cents;
public Currency(uint dollars, ushort cents)
{
this.Dollars = dollars;
this.Cents = cents;
}
public override string ToString()
{
return string.Format("${0}.{1,-2:00}", Dollars, Cents);
}
public static implicit operator float(Currency value)
{
return value.Dollars + (value.Cents / 100.0f);
}
public static explicit operator Currency(float value)
{
checked
{
uint dollars = (uint)value;
ushort cents = Convert.ToUInt16((value - dollars) * 100);
return new Currency(dollars, cents);
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
//Console.WriteLine(2500000.ToString("N"));
Currency balance = new Currency(50, 35);
Console.WriteLine(balance);
Console.WriteLine(balance.ToString());
Console.WriteLine("balance is" + balance);
Console.WriteLine("balance is(using ToString())"+
balance.ToString());
float balance2 = balance;
Console.WriteLine("After converting to float,=" + balance2);
balance = (Currency)balance2;
Console.WriteLine("After convering to Currency,=" + balance);
Console.WriteLine("Now attempt to convert out of range value of" +
"-$100.00 to a Currency");
checked
{
balance = (Currency)(-50.5);
Console.WriteLine("Result is " + balance.ToString());
}
}
catch (Exception e)
{
Console.WriteLine("Exception occurred:" + e.Message);
}
}
}
}
不是很理解Console.WriteLine(balance); 輸出是50.35
Console.WriteLine("balance is" + balance); balance是$50.35
balance.ToString() 是$50.35我都是理解的
求好心人給我講一下 有點暈
因為有 implicit operator float
,所以 WriteLine(balance)
匹配的是 WriteLine(float value)
(你可以在WriteLine上“右鍵\轉到定義”進行確認)。
按 float 而不是 object 輸出,不會調用 ToString()
。
你把 implicit operator float
去掉,就會輸出 $50.35 了。