C# 创建自定义转换

来源:互联网 发布:cf抽奖算法 编辑:程序博客网 时间:2024/05/28 05:18

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 < Height;i++ )
            {
                for (int j = 0; j < Width; j++)
                {
                    System.Console.Write("*");
                }
            }
        }

        public override string ToString()
        {
            return string.Format("Width: {0},Heigth: {1}",this.Width,this.Height);
        }
    }

    public class Square
    {
        public int Length { get; set; }

        public Square();

        public Square(int i)
        {
            this.Length = i;
        }

        public void Draw()
        {
            for (int m = 0; m < Length;m++ )
            {
                for (int n = 0; n < Length; n++)
                {
                    System.Console.Write("*");
                }
            }
        }

        public override string ToString()
        {
            return string.Format("Length: {0}",this.Length);
        }

        /// <summary>
        /// 矩形可显示转换为正方形
        /// </summary>
        public static explicit operator Square(Rectangle c)
        {
            Square s = new Square();
            s.Length = c.Height;
            return s;
        }
    } 

Rectangle r = new Rectangle() { Width = 4,Height = 3 };
                Square s = (Square)r;
                s.Draw();

0 0
原创粉丝点击