2011-11-15 24 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); 
} 
相关问题