CSDN广告是越来越多了,所有博客笔记不再更新,新网址 DotNet笔记
1:什么是接口(interface)
接口是一种规范。个人观点,没有接口,也不会影响我们正常编程。C++不是如此吗?
2:接口和类的几个区别
1)接口不能使用访问修饰付,因为接口都是公有的。
2)接口成员不能拥有实现代码。
3)接口不能独立存在,必须依靠类。
4)接口接口成员不能使用sealed(类的密封,不能拥有子类),virtural,abstract,static!原因是,没有意义,仔细思考会发现逻辑上不通!
5)接口不能定义字段成员。
6)接口馁定义的方法必须要被实现。如果不想去实现,可以在子类中用new关键字隐藏。
7) 接口不可以拥有字段,但是可以拥有属性,拥有方法。其属性必须去实现。
3:接口的实现:
1)隐式实现 可以通过类对象调用实现后的函数
2)显示实现 只能通过接口访问
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace interface_ns
{
interface interf1
{
void DoSomeThingB();
void DoSomeThingA();
}
class A : interf1
{
public void DoSomeThingB()//隐式实现了DoSomeThingB();
{
Console.WriteLine("隐式实现的B函数!");
}
void interf1.DoSomeThingA()//显示实现了DoSomeThingA();只能通过接口对象访问!
{
Console.WriteLine("显示实现的A函数!");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.DoSomeThingB();
//通过接口调用显示实现的方法!
interf1 i = new A();
i.DoSomeThingA();
//通过接口调用显示实现的方法!
interf1 j = a;
j.DoSomeThingA();
Console.Read();
}
}
}
结果: