天天看點

C#自定義類型轉換C#自定義類型轉換

C#自定義類型轉換

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立一個矩形
            Rectangle r = new Rectangle(15, 4);
            Console.WriteLine(r.ToString());
            r.Draw();

            Console.WriteLine();

            //根據矩形栓換為正方形
            Square s = (Square)r;
            Console.WriteLine(s.ToString());
            s.Draw();
            Console.WriteLine();
        }
    }

    public struct Rectangle
    {
        public int Width { get; set; }
        public int Height { get; set; }

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

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

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

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

        public Square (int l):this()
        {
            Length = l;
        }

        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 = {0}]", Length);
        }

        //矩形可顯示的轉換為正方形
        //implicit:隐式轉換
        //explicit: 顯示轉換
        public static explicit operator Square(Rectangle r)
        {
            Square s = new Square();
            s.Length = Math.Min(r.Width, r.Height);
            return s;
        }
    }
}