0

类型转换运算符在 c++ 中很酷,在 c# 中没有这样的东西吗?

C++代码:

class A
{
int dat;

public:
A(int num = 0 ) : dat(num) {}

operator int() {return dat;} // cast to int
};
4

3 回答 3

4

C#有!这里有几个来自 MSDN 的例子:明确的:

public static explicit operator Celsius(Farenheit f)
{
    return new Celsius((5.0f/9.0f)*(f.degrees-32));
}

隐式:

//  User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
    return new Digit(d);
}
于 2010-01-28T17:02:26.200 回答
1

由于隐式和显式转换运算符都是一元运算符,因此可以像其他一元运算符一样使用语法覆盖它们。以下是隐式转换运算符的一般语法:

public static implicit operator result-type(op-type operand)
于 2010-01-28T17:03:48.207 回答
0

您在寻找什么特定功能?对于类的类型转换,您可以通过转换为类型 ((BaseClass)o) 语法来降级对基类的引用。您可以通过 Convert.ToInt32("223"); 将引用转换为其他类型。对于实现 IConvertible 的类型。你在找什么具体的?

HTH。

于 2010-01-28T17:02:38.027 回答