开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜