C#继承练习2

using System;
using System.Collections.Generic;
using System.Text;

namespace HELLO
{
    class 矩形
    {
        static void Main(string[] args)
        {
            Example ex = new Example();//实例化
            Example ex1 = new Example(1, 2);//实例化
            Example2 example2 = new Example2(4, 6);
            Console.WriteLine("面积为{0}", example2.area());
            // 创建一个 List<Shape> 对象,并向该对象添加 Circle和 Rectangle
            var shape = new List<Shape> { new Circle(), new Rectangle() };
            // 使用 foreach 循环对该列表的派生类进行循环访问,并对其中的每个 Shape 对象调用 Draw 方法
            foreach (var item in shape)
            {
                item.X = 4;
                item.Y = 5;
                item.Draw();
                item.Area();
            }
        }
    }
    class Example
    {
        public Example(int a, int b)
        {
            Console.WriteLine("您这个是有参构造函数,分别输入了{0}和{1}", a, b);
        }
        public Example() { Console.WriteLine("您这个是无参构造函数"); }
    }
    abstract class Example1
    {
        abstract public int area();
    }
    class Example2 : Example1
    {
        private int a, b;
        public Example2(int a, int b)
        { this.a = a; this.b = b; }
        public override int area()
        {
            return a * b;
        }
    }
    public class Shape//父类
    {
        internal int x,y;
        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
        public virtual void Draw() { Console.WriteLine("我要画图形"); }
        public virtual void Area() { int area = x + y; Console.WriteLine("面积是{0}", area); }
    }
    public class Circle : Shape//派生类1
    {
        public override void Draw()//重写方法1
        {
            Console.WriteLine("我要画一个圆");
            base.Draw();
        }
        public override void Area()//重写方法2
        {
            int area = 3 * x * y;
            Console.WriteLine("面积是{0}", area);
        }
    }
    public class Rectangle : Shape//派生类2
    {
        public override void Draw()
        {
            Console.WriteLine("我要画一个矩形");
            base.Draw();
        }
        public override void Area()
        {
            int area = x * y;
            Console.WriteLine("面积是{0}", area);
        }
    }
}

C#继承练习2

C#继承练习2

上一篇:C# webapi 权限验证


下一篇:Windows设置了环境变量,环境变量依然报错