C#抽象类不能实例化,只能被继承。抽象成员没有实现,必须在非抽象的派生类中重写并提供实现。
·
1. 抽象类 (Abstract Class)
-
不能被实例化:只能作为基类被继承
-
可以包含抽象成员和非抽象成员
-
使用场景:定义通用模板,要求派生类实现特定行为
-
public abstract class Shape // 抽象类声明 { public abstract double Area(); // 抽象方法(无实现) public void Display() // 非抽象方法(有实现) { Console.WriteLine("This is a shape"); } }2. 抽象成员 (Abstract Members)
-
必须存在于抽象类中
-
不包含具体实现(无方法体)
-
强制派生类用
override实现 -
支持类型:方法、属性、索引器、事件
-
pulic abstract class Animal { // 抽象属性 public abstract string Name { get; } // 抽象方法 public abstract void MakeSound(); } public class Dog : Animal { public override string Name => "Dog"; // 属性实现 public override void MakeSound() // 方法实现 { Console.WriteLine("Woof!"); } }几个感悟:1、子类只能通过继承基类实现;2、抽象的属性成员必须全部在子类实现;3、子类可以调用抽象类方法
-
以下是具体应用的代码
-
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { /// <summary> /// 移动存储设备父类 /// </summary> public abstract class StorageDevicecs { public abstract void Read(); public abstract void Write(); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { public class UDISK : StorageDevicecs { public override void Read() { Console.WriteLine("U盘读取中"); } public override void Write() { Console.WriteLine("U盘写入中中"); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { public class mp3 : StorageDevicecs { public override void Read() { Console.WriteLine("mp3读取中"); } public override void Write() { Console.WriteLine("mp3写入中中"); } public void playmusic() { Console.WriteLine("LALALLAALLALLALA,xxxx"); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { public class Mobile_Harddrive : StorageDevicecs { public override void Read() { Console.WriteLine("移动硬盘读取中"); } public override void Write() { Console.WriteLine("移动硬盘写入中"); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { public class Computer { public StorageDevicecs SD { get; set; } public void Cread() { SD.Read(); } public void CWrite() { SD.Write(); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace outstorge { class Program { static void Main(string[] args) { Computer cp = new Computer(); cp.SD = new mp3(); cp.Cread(); cp.CWrite(); mp3 mpx= new mp3(); ///注意此处 mpx.playmusic(); Console.ReadKey(); } } }
更多推荐



所有评论(0)