用户定义的类型转换

定义类Angle,代表几何中的角度。

public class Angle 
{
    private readonly int degrees;//度
    private readonly int minutes;//分
    private readonly int seconds;//秒
    public Angle(int degrees, int minutes, int seconds)
    {
        this.degrees = degrees;
        this.minutes = minutes;
        this.seconds = seconds;
    }

    public override string ToString()
    {
        return string.Format("{0}°?{1}′?{1}″?", degrees, minutes, seconds);
    }

    public static implicit operator float(Angle angle)
    {
        return (float)angle.degrees + (float)angle.minutes / 60 + (float)angle.seconds / 3600;
    }

    public static explicit operator Angle(float angle)
    {
        int degrees = (int)angle;
        int minutes = (int)((angle - degrees) * 60);
        int seconds = (int)((angle - degrees) * 3600 - minutes * 60);
        return new Angle(degrees, minutes, minutes);
    }
}

其中,implicit代表隐式转换,explicit代表显式转换。

class Program
{
    static void Main(string[] args)
    {
         Angle angle = new Angle(35, 26, 46);
         Console.WriteLine("角度为:{0}",angle.ToString());
         float fAngle = angle;
         Console.WriteLine("转换成float后角度为:{0}°", fAngle.ToString());
         Angle angle1 = (Angle)fAngle;
         Console.WriteLine("再次转换成Angle后角度为:{0}°", angle1.ToString());
    }
}

注意:隐式转换与显式转换的用法。

执行结果如下图所示。


 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值