2016-04-15 129 views
1

我有一個庫,它接收並返回一個字符串(我想創建無限數字,但我簡化了解釋)。用值覆蓋對象類型

我有我的操作符重載多源庫,但是當我使用的庫:

MyType foo = new MyType("10"); 
MyType bar = foo + foo; 
Console.WriteLine("{0}", bar.GetType()); 
Console.WriteLine("{0}", bar); 
Console.WriteLine("{0}", bar.Value); // Redundant: the property "Value" has the value as string 

輸出是:

MyNamespace.MyType 
MyNamespace.MyType // The object "bar" returns the object type 
10 

好,但我希望得到「10」( bar.Value)僅使用對象名稱「欄」:

Console.WriteLine("{0}", bar); 
// I want the next output: 10 

我想這樣做在與變化的GetType()庫(我發現這是不可能超越的GetType()):

public new string GetType() 
{ 
    return this.Value; 
} 

但這隻能用「bar.GetType()」,而不是與「酒吧」的作品。

我認爲在C#中是不可能的。

回答

3

這可以很容易地通過重寫Object.ToString()來完成:

class MyType 
{ 
    public string Value { get; set; } 
    public override string ToString() { return this.Value; } 
} 

測試:

MyType m = new MyType("10"); 
Console.WriteLine(m); 

打印10

Explenataion:當致電WriteLine時,班級'ToString - 方法被調用。如果此方法在類型中未被覆蓋,則使用默認實現object,它將簡單地返回類的類型,在您的情況下爲MyNamespace.MyType

+0

有了這個我已經overrided toString()和它的工作原理,但在源使用toString()和行爲是默認的,而不是overrided。它是通用的,但爲什麼如果我重寫它,不要改變源代碼中的行爲? – Joe