문제

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