typecast operator is cool in c++, no such thing in c#?
c++ code:
class A
{
int dat;
public:
A(int num = 0 ) : dat(num) {}
operator int() {return dat;} // cast to int
};
C# has! here couple examples from MSDN: Explicit:
public static explicit operator Celsius(Farenheit f)
{
return new Celsius((5.0f/9.0f)*(f.degrees-32));
}
Implicit:
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
Since both implicit and explicit cast operators are unary operators, they can be overridden using syntax like other unary operators. Here is the general syntax for the implicit conversion operator:
public static implicit operator result-type(op-type operand)
What specific feature are you looking for? For type conversion of classes, you can downgrade references to the base class by converting to type ((BaseClass)o) syntax. You can convert references to other types via Convert.ToInt32("223"); for types that implement IConvertible. What specific are you looking for?
HTH.
精彩评论