Is it possible to cast string into my own type?
-
01-03-2021 - |
题
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;
I believe this operator does what you want (as part of your Currency class):
public static explicit operator Currency(stringvalue){
return new Currency(value);
}
不隶属于 StackOverflow