作用:
用于强制转换
当涉及到用户自定义的类时,可以使用explicit将一个类的实例强制转换为另一个类的实例
举例:
Farenheit和Celsius 是两个用户自定义的类。
现在需要将Farenheit类的一个对象强制转换为Celsius类型的对象,这个时候不能用传统的方法强制转换。
解决方法是在Farenheit类的定义中添加相关代码,使其对象能够转换为Celsius类型的对象
代码
//定义Fahrenheit类 class Fahrenheit { public Fahrenheit(float temp) //构函 { degrees = temp; } //通过这段代码,允许Fahrenheit类的对象按照指定的规则强制转换为Celsius类型的对象 //explicit 一般需要配合static和operator运算符使用 public static explicit operator Celsius(Fahrenheit f) { return new Celsius((5.0f / 9.0f) * (f.degrees - 32)); } public float Degrees //属性 { get { return degrees; } } private float degrees; //变量 }
//定义Celsius类
class Celsius
{
public Celsius(float temp)
{
degrees = temp;
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}
//使用强制转换
class MainClass
{
static void Main()
{
Fahrenheit f = new Fahrenheit(100.0f);//实例化一个Fahrenheit对象f
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f; //将f强制转换为Celsius类型的对象c
Console.Write(" = {0} celsius", c.Degrees);
}
}