没有在C#中的类的类型转换运算符?
问题描述:
typecast运算符在C++中很酷,在c#中没有这样的事情?没有在C#中的类的类型转换运算符?
C++代码:
class A
{
int dat;
public:
A(int num = 0) : dat(num) {}
operator int() {return dat;} // cast to int
};
答
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);
}
答
你在找什么特殊功能?对于类的类型转换,可以通过转换为type((BaseClass)o)语法来降级对基类的引用。您可以通过Convert.ToInt32(“223”);将引用转换为其他类型。对于实现IConvertible的类型。你在找什么具体的东西?
HTH。
答
由于隐式和显式转换运算符都是一元运算符,因此可以像使用其他一元运算符一样使用语法覆盖它们。下面是隐式转换运算符的一般语法:
public static implicit operator result-type(op-type operand)
下一次,请在第一次提问时尝试清楚具体。它会帮助你避免接近的选票。 – 2010-01-28 17:11:19
@jeffamaphone,有你。 – Benny 2010-01-28 17:14:03