参考代码1:
using System; namespace InterfaceDemo { /// <summary> /// 定义一个爬树接口 /// </summary> interface IClimbTree { void ClimbTree(); } /// <summary> /// 定义一个抓老鼠接口 /// </summary> interface ICatchMouse { void CatchMouse(); } /// <summary> /// 定义站立行走接口 /// </summary> interface IStandWalk { void StandWalk(); } /// <summary> /// 定义一个宠物类 /// </summary> public class Pet { protected string Gene = "Pet"; public void Run() { Console.WriteLine("我会跑"); } } /// <summary> /// 猫类,继承于宠物类,又实现了爬树和抓老鼠接口 /// </summary> public class Cat : Pet, IClimbTree, ICatchMouse { public void ClimbTree() { Console.WriteLine("我会爬树"); } public void CatchMouse() { Console.WriteLine("我会抓老鼠"); } } /// <summary> /// 站立猫类,继承于猫类,又实现了站立行走接口 /// </summary> public class StandCat :Cat, IStandWalk { public void StandWalk() { Console.WriteLine("我会站立行走"); } public void WhoAreYou() { Console.WriteLine(Gene + " Class Animal"); } } class Program { static void Main(string[] args) { Cat cat = new Cat(); cat.Run(); cat.ClimbTree(); cat.CatchMouse(); StandCat standCat = new StandCat(); standCat.StandWalk(); standCat.WhoAreYou(); Console.ReadLine(); } } }
参考代码2:
using System; namespace LearnFromComradeLeiFeng { public class School : IPartyCenter, IStateCouncil { public void NormalTeach() { Console.WriteLine("学校正常教学工作..."); } void IPartyCenter.LearnFromComradeLeiFeng() { Console.WriteLine("学校具体落实向雷锋同志学习的号召...."); } public void EpidemicPreventionWork() { Console.WriteLine("学校具体落实全校抗疫的指导方针...."); } } public class Army : IPartyCenter, IStateCouncil { public void ReadyToFight() { Console.WriteLine("时刻准备打仗..."); } void IPartyCenter.LearnFromComradeLeiFeng() { Console.WriteLine("军队具体落实向雷锋同志学习的号召...."); } public void EpidemicPreventionWork() { Console.WriteLine("军队具体落实全军抗疫的指导方针...."); } } interface IPartyCenter { public void LearnFromComradeLeiFeng(); } interface IStateCouncil { void EpidemicPreventionWork(); } class Program { static void Main(string[] args) { School sc = new School(); Army am = new Army(); sc.NormalTeach(); sc.EpidemicPreventionWork(); am.ReadyToFight(); am.EpidemicPreventionWork(); IPartyCenter pc = null; pc=(IPartyCenter) sc; ((IPartyCenter)pc).LearnFromComradeLeiFeng(); pc = (IPartyCenter)am; ((IPartyCenter)pc).LearnFromComradeLeiFeng(); } } }