您的位置:首页 > 编程语言 > C#

C# 中关于接口实现、显示实现接口以及继承

2017-08-29 09:30 309 查看
接口以及抽象类、实现类

public interface IA

{

void H();

}

public interface IB

{

void H();

}

public abstract class D

{

public abstract void H();

}

public class C : D,IA, IB

{

void IA.H()

{

Console.WriteLine("all a.h");

}

public override void H()//T

{

Console.WriteLine("all b.h");

}

}

复制代码

如果类C继承了抽象类D,那么在类C中可以使用override关键字,接口IB调用的也是被覆盖的方法H(T位置)【可以理解T位置的方法H同事覆盖了抽象类D中的方法H和实现了接口IB中的方法H】。

如果类C不继承抽象类D,那么类C中不能使用override关键字,override关键字只能在继承抽象类的情况下使用(个人使用之后感觉是这样的)。

一开始的代码是这样的:

public interface IA

{

void H();

}

public interface IB

{

void H();

}

public abstract class D

{

public abstract void H();

}

public class C : D,IA, IB

{

public override void H()

{

Console.WriteLine("all h");

}

void IA.H()

{

Console.WriteLine("all a.h");

}

void IB.H()

{

Console.WriteLine("all b.h");

}

}

复制代码

显示实现接口。显示实现接口时不能在覆盖的方法或字段上使用访问权限关键字【private、protected、public等】

在不继承抽象类D的情况下是这样的:

public class C : IA, IB

{

public void H()//U

{

Console.WriteLine("all h");

}

void IA.H()

{

Console.WriteLine("all a.h");

}

void IB.H()

{

Console.WriteLine("all b.h");

}

}

复制代码

调用时,接口IA的对象只能访问IA.H(),接口IB只能访问IB.H(),访问不到U位置的方法。只能在实例化类C的情况下才能访问到U位置的方法H

调用的代码:

class Program

{

static void Main(string[] args)

{

IA a = new C();

IB b = new C();

a.H();

b.H();

D d = new C();

d.H();

C c = new C();

c.H();

Console.WriteLine("Hello World!");

Console.ReadLine();

}

}

复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: