是否可以将字符串转换为我自己的类型?

Sex*_*yMF 2 .net c# casting custom-type

public class Currency{
    private Code {get;set;}
    public Currency(string code){
      this.Code = code;
    }
    //more methods here
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使我的对象成为可投射的

string curr = "USD";
Currency myType = (Currency)curr;
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用构造函数来完成它,但是我在不需要初始化对象的情况下使用了我需要的地方...

我也相信生病需要像FromString()这样做的功能
谢谢.

jas*_*son 6

是的,只需添加一个显式的转换运算符:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以说:

string curr = "USD";
Currency myType = (Currency)curr;
Run Code Online (Sandbox Code Playgroud)