程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> string-C# 重寫ToString()與調用問題

string-C# 重寫ToString()與調用問題

編輯:編程解疑
C# 重寫ToString()與調用問題

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 了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved