c# 抽象类

c#抽象类

csharp 复制代码
namespace demo1
{
    /// <summary>
    /// 抽象类是作为一种抽象的概念,是基类
    /// 在抽象类中声明方法,加上abstract就是抽象方法。所有有抽象类派生出来的都要重载实现抽象方法
    /// 抽象方法不可以使用virtual、static、和prevate修饰
    /// 抽象方法提供一个声明,不提供具体实现
    /// 抽象类不能直接实例化
    /// 抽象类不能被密封
    /// 抽象类可以包含抽象成员,非抽象类不可以
    /// </summary>    
    
    
    //定义一个基类shape
    public abstract class Shape
    {
        protected string Color;// protected 可以允许派生类访问它的基类成员
        public Shape(string color) //构造函数
        {
            this.Color = color;
        }
        public string GetColor()
        { return this.Color; }
        public abstract double GetArea();

    }
    //定义一个cirle类
    public class Cirle : Shape
    {
        //prevate 只有在同一个类中可以访问
        private double Radius; 
        public Cirle(string color,double radius):base(color)
        {
            this.Color=color;
            this.Radius = radius;
        }
        public override double GetArea() //继承基类必须重载抽象方法
        {
            return System.Math.PI * this.Radius*this.Radius;
        }
    }

    internal class Progrom
    {
        static void Main(string[] args)
        {
            Cirle a=new Cirle("黄色",1);
            double b=a.GetArea();
            Console.WriteLine(b);
        }
 

    }

}

c#密封类

csharp 复制代码
namespace demo1
{
    /// <summary>
    /// 密封类:如果所有类都可以被继承,那么很容易导致继承的滥用,进而使类的层次结构体系变得十分复杂,这样会使开发人员对类的理解和使用变得十分困难。为了避免滥用继承,C#中提出了密封类的概念。
    /// 密封类可以用来限制扩展性,如果密封了某个类,则其他类不能从该类继承;
    /// 如果密封了某个成员,则派生类不能重写该成员的实现
    /// 
    /// </summary>

    internal class Progrom
    {
        public class Myclass1 
        { 
            public virtual void Write()
            {
                Console.WriteLine("class1 这是一个未密封的方法");//这是一个虚函数,可以被重写
            }
        }
        public class Myclass2:Myclass1
        {
            //继承之后可以对虚方法进行重写
            public sealed override void Write()
            {
                Console.WriteLine("这是myclass2中密封的方法");
            }

        }
        public class Myclass3 : Myclass2
        {
            //继承之后可以对虚方法进行重写
            //public  override void Write()
            //{
                ///这是密封的,不可以在进行重写
            //}

        }


        static void Main(string[] args)
        {
           Myclass1 a = new Myclass1();
            a.Write();
            Myclass2 b = new Myclass2();
            b.Write();  
        }
 

    }

    
}
相关推荐
唐青枫4 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201010 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5