2011-11-15 25 views
2
public class Currency{ 
    private Code {get;set;} 
    public Currency(string code){ 
     this.Code = code; 
    } 
    //more methods here 
} 

我希望能夠讓我的對象澆注料是否可以將字符串轉換爲我自己的類型?

string curr = "USD"; 
Currency myType = (Currency)curr; 

我知道,我可以用構造器做到這一點,但我已經用例,我需要投不初始化對象...

我也認爲生病需要像FromString()這樣的功能來做
謝謝。

+0

看吧http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs .71).aspx –

回答

4

此方法添加到您的貨幣類:

public static explicit operator Currency(String input) 
{ 
    return new Currency(input); 
} 

,並調用它是這樣的:

Currency cur = (Currency)"USD"; 
+0

謝謝。我可以將它轉換回字符串嗎? –

3

如果您爲自己的類型創建了自己的施法操作符,則可以使其成爲可能。

查看implicitexplicit的關鍵字。

(在這種情況下,我寧願顯式演員)。

6

是,只需添加一個explicit cast operator

public class Currency { 
    private readonly string code; 
    public string Code { get { return this.code; } } 
    public Currency(string code) { 
     this.code = code; 
    } 
    //more methods here 

    public static explicit operator Currency(string code) { 
     return new Currency(code); 
    } 
} 

現在你可以說:

string curr = "USD"; 
Currency myType = (Currency)curr; 
0

我相信這個操作你想要做什麼(如貨幣類的一部分):

public static explicit operator Currency(stringvalue){ 
    return new Currency(value); 
} 
相關問題