explicit

作用:

        用于强制转换
        当涉及到用户自定义的类时,可以使用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);
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值