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

C# 接口的特点、接口的作用、接口的简单应用

2017-05-31 17:18 387 查看
使用接口的目的就是实现面向对象的多态。接口用来描述一种行为。

对于继承父类与接口的类(前提是接口实现是普通实现而非显示实现),在实现的时候还是先实现自己类的方法;若接口为显示实现时,实现方法为接口的方法。

总结:

1、接口存在的意义是为了实现多态;

2、接口中只能包含方法(属性、事件、索引);

3、接口的成员不能有任何实现;(类似于抽象类)

4、接口不能被实例化;静态类、抽象类也不可以被实例化

5、接口的成员不能有访问修饰符(默认为public);

6、实现接口的子类必须将接口的所有成员函数实现;(类似于抽象类)

7、子类实现接口的方法时,不需要任何关键字,直接实现即可。(抽象类、虚方法需要加override)

namespace Inter
{
class Program
{
static void Main(string[] args)
{
Interable inn=new stinter (); //定义一个接口
inn.Sendable();
Console.ReadKey();
}
}

public interface Interable
{
void Sendable();// 接口中成员访问修饰符默认为public,但是不能加
}

public class stinter : Interable //继承了接口,必须要实现接口的成员
{
public void Sendable()
{
Console.WriteLine("That can send the message");
}
}

public class teinter : Interable
{
public void Sendable()
{
Console.WriteLine("the message");
}
}

public class soninter // 定义了一个父类
{
public void Sendable()
{
Console.WriteLine("The father class soninter");
}
}

    // 对于继承父类与接口的类(前提是接口是普通实现而非显示实现),在实现的时候还是先实现自己类的方法;若接口为显示实现时,实现方法为接口的方法。

 

public class teinter : soninter, Interable // 这时候需要继承一个父类,一个接口,位置上把父类放在前面
{
// 这是一种普通的接口实现方法
// 当然也可以显示实现接口方法,可以解决方法的重名问题

public void Sendable()// 这个是必须要实现接口的方法,与父类的方法名相同,所以父类的方法隐藏 了;
{
Console.WriteLine("the message");
}

// 当自己的方法与接口的方法重名时,需要显示的实现接口的方法,这时候实现的方法是接口的
void Interable.Sendable ()
{
Console.WriteLine("这是一种显示的实现接口的方法");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: