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

I want to be able to make my object castable

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

I know that I can do it with the contructor, but I have usecase where I need to cast without initializing the object...

I also believe that ill need a function like FromString() to do it
Thanks.

有帮助吗?

解决方案

Add this method to your Currency class:

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

And call it like this:

Currency cur = (Currency)"USD";

其他提示

Yes, just add an 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);
    }
}

Now you can say:

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

If you create your own cast-operators for your type, you can make this possible.

check out the implicit and explicit keywords.

(in this case, I'd prefer an explicit cast).

I believe this operator does what you want (as part of your Currency class):

public static explicit operator Currency(stringvalue){
    return new Currency(value);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top