黑马程序员-------运算符重载(三)

 ---------------------- <a href=" http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href=" http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------

转换运算符的重载,其中的关键字是implicit (隐式转换),explicit(显式转换)

格式如下: public static implicit/explicit  operator  targetType ( source type   o)

但是,转换运算符也有几点需要注意:

一、这两种运算符主要用于自定义的类之间的转换,或者,自定义类与内置类型的转换,但是不能全用于内置类型的转换,也就是说,至少要有一种是自定义的类型。

二、基类与派生类也无法再其中转换,而object为所有类的基类,因此,也不允许做转换。

三、自己在定义的时候要明确使用显示转换还是隐式转换,因为,如果用隐式转换,是系统自动完成的,很可能遇到数据丢失的情况,因此,在定义转换方式之前,要确定应该用那种方式。

下面是定义了一个转换的过程:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace _06

{

    class Program

    {

        static void Main(string[] args)

        {

            long  l;

            Rangle r = new Rangle(10, 20);

            l = r;

            Console.WriteLine(l);

            Squre s = (Squre)r;

            l = s.sarea;

            Console.WriteLine("s.area="+l);

            Rangle r1 = (Rangle)s;

            Console.WriteLine(r1.length);

            Console.WriteLine(r1.rarea);

            Console.ReadKey();

        }

    }

    class Rangle

    {

        public int  rarea ;

        public int length;

        public int width;

        public Rangle(int length,int width)

        {

            this.length = length;

            this.width = width;

            rarea=length*width;

        }

        public static implicit operator long(Rangle r)

        {

            long l = r.rarea;

            return l;

        }

        public static explicit operator Squre(Rangle r)

        {

            Squre s = new Squre(r.width);

            return s;

        }

    }

    class Squre

    {

        public long sarea;

        public int m;

        public Squre(int m)

        {

            this.m = m;

            sarea = m * m;

        }

        public static explicit operator Rangle(Squre s)

        {

            int m1 = (int)s.sarea;

            Rangle r = new Rangle(m1,m1);

            return r;

        }

    }

}

 ---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值