參考代碼1:
using System; namespace InterfaceDemo { /// <summary> /// 定義一個(gè)爬樹接口 /// </summary> interface IClimbTree { void ClimbTree(); } /// <summary> /// 定義一個(gè)抓老鼠接口 /// </summary> interface ICatchMouse { void CatchMouse(); } /// <summary> /// 定義站立行走接口 /// </summary> interface IStandWalk { void StandWalk(); } /// <summary> /// 定義一個(gè)寵物類 /// </summary> public class Pet { protected string Gene = "Pet"; public void Run() { Console.WriteLine("我會(huì)跑"); } } /// <summary> /// 貓類,繼承于寵物類,又實(shí)現(xiàn)了爬樹和抓老鼠接口 /// </summary> public class Cat : Pet, IClimbTree, ICatchMouse { public void ClimbTree() { Console.WriteLine("我會(huì)爬樹"); } public void CatchMouse() { Console.WriteLine("我會(huì)抓老鼠"); } } /// <summary> /// 站立貓類,繼承于貓類,又實(shí)現(xiàn)了站立行走接口 /// </summary> public class StandCat :Cat, IStandWalk { public void StandWalk() { Console.WriteLine("我會(huì)站立行走"); } 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("學(xué)校正常教學(xué)工作..."); } void IPartyCenter.LearnFromComradeLeiFeng() { Console.WriteLine("學(xué)校具體落實(shí)向雷鋒同志學(xué)習(xí)的號(hào)召...."); } public void EpidemicPreventionWork() { Console.WriteLine("學(xué)校具體落實(shí)全校抗疫的指導(dǎo)方針...."); } } public class Army : IPartyCenter, IStateCouncil { public void ReadyToFight() { Console.WriteLine("時(shí)刻準(zhǔn)備打仗..."); } void IPartyCenter.LearnFromComradeLeiFeng() { Console.WriteLine("軍隊(duì)具體落實(shí)向雷鋒同志學(xué)習(xí)的號(hào)召...."); } public void EpidemicPreventionWork() { Console.WriteLine("軍隊(duì)具體落實(shí)全軍抗疫的指導(dǎo)方針...."); } } 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(); } } }
浙公網(wǎng)安備 33010602011771號(hào)