开发者

no typecast operator for class in c#? [closed]

开发者 https://www.devze.com 2022-12-18 14:02 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifyin开发者_如何学运维g this question so that it can be reopened, visit the help center. Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号