zoukankan      html  css  js  c++  java
  • C#无继承类间的转换explicit 关键字

     回顾1:

         1:数值转换,对于内建数值(sbyte,int,float等),如果在较小容器中存储较大的数值,就需要一个显式转换,因为这可能导致数据丢失。这实际上就是告诉编译器:

    别理我,我知道我在做什么。反过来,如果试图将较小类型放到指定目标类型中时不会丢失数据,将 自动进行隐式转换:

       int a=123;

      long b=a;

       int c=(int)b;

       2:类类型转换:

            类类型可通过传统的继承关系(is-a关系)关联起来。这时,C#转换过程允许我们向类层次结构中的上级或下级进行强制类型转换。

    而当两个没有关系的两个类型时怎么转换呢如下:

    定义类Rectangle
     public class Rectangle
    {
    public int Width { get;set;}
    public int Height { get; set; }

    public Rectangle() { }
    public Rectangle(int w,int h)
    {
    this.Width = w;
    this.Height = h;
    }

    public void Draw()
    {
    for (int i = 0; i < Width; i++)
    {
    for (int j = 0; j < Height; j++)
    {
    Console.Write(" *");
    }
    Console.WriteLine();
    }
    }
    public override string ToString()
    {
    return string.Format("[Width is :{0}, Height is :{1}]", Width, Height);
    }

    //在这定义个隐式类型转换例程
    public static implicit operator Rectangle(Square s)
    {
    Rectangle r = new Rectangle();
    r.Width = s.Length;
    r.Height = s.Length * 2;
    return r;
    }
    }
    定义类Square
     public class Square
    {
    public int Length { get; set; }

    public Square(int l)
    {
    Length = l;
    }
    public Square() { }
    public void Draw()
    {
    for (int i = 0; i < Length; i++)
    {
    for (int j = 0; j < Length; j++)
    {
    Console.Write(" *");
    }
    Console.WriteLine();
    }
    }

    public override string ToString()
    {
    return string.Format("[Length is {0}]",Length);
    }

     矩形可显示转换为正方形
            注意,Square类型的这个版本定义了一个显示转换操作符。如同重载操作符过程一样,转换例程使用C#operater 结合eplicit
            而且必须为静态的。传入参数是要转换的实体,而操作符类型是要转换后的类型实体。
                      客观来讲,将Square转换为int可能不是最直观的操作。不过,这确实让我们发现关于自定义转换例程非常重要的一点:
            

    重载自定义类型转换
     public static explicit operator Square(Rectangle r)
    {
    Square s = new Square();
    s.Length = r.Height;
    return s;
    }

    public static explicit operator Square(int sideLength)
    {
    Square newSq = new Square();
    newSq.Length = sideLength;
    return newSq;
    }

    public static explicit operator int(Square s)
    {
    return s.Length;
    }

    }


    只要代码语法书写正确,编译器并不关心由什么转换成什么。

    运行结果:


             

  • 相关阅读:
    03 java中的基本数据类型和运算符
    02 Eclipse安装
    01 HelloWorld
    express不是内部或外部命令
    win10 内存或系统资源不足,无法打开PPT
    win 10中解决“此文件在另外一个进程中运行”的问题
    后台查找密码暴力破解
    DVWA--全等级暴力破解(Burte Force)
    DVWA简单搭建
    破解版
  • 原文地址:https://www.cnblogs.com/haofaner/p/2405737.html
Copyright © 2011-2022 走看看