C# 接口(Interface)
来源:互联网 发布:网络统考成绩查询短信 编辑:程序博客网 时间:2024/05/21 09:10
接口的概念:
由于C# 语言不支持多重继承,所以该功能很重要。此外,您必须使用接口,如果要模拟结构的继承,因此他们不能从另一个机构或选件类实际继承。如下面的实例所示,通过使用Interface 关键字,定义一个借口。
interface USB
{
void Read(string[] datas);
}
接口的属性:
1.实现接口的任何类或结构必须实现其所有的成员方法。
2.接口不能直接实例,但是可以通过指向子类间接实例化。
3.接口可以包含方法和属性的声明,但是不能包含字段。
4.接口中所有方法、属性默认为public ,不能在后面再添加修饰符。
5.类或结构可以实现多个接口。类可以继承基类并实现一个或多个接口。
例如:键盘 和鼠标 都实现类 USB 接口
interface IUSB //USB接口 { void Read(); } class Keyboard : IUSB //实现USB接口 { public void Read() { Console.WriteLine("Keyboard's ReadMethod"); } } class Mouse : IUSB { public void Read() { Console.WriteLine("Mouse's ReadMethod"); } } class MainClass { public static void Main(string[] args) { IUSB usb = (IUSB)new Keyboard(); usb.Read(); usb = (IUSB)new Mouse(); usb.Read(); } }
接口和抽象类
接口与抽象类非常相似,它定义类一些未实现的属性和方法。所有继承它的类都继承这些成员,在这个角度上,可以把接口理解为一个类的模板。接口最终的目的是起到统一的作用。
相同点
1、两者都包含可以由子类继承的抽象成员;
2、两者都不直接实例化。
不同点
1、抽象类除拥有抽象成员之外,还可以拥有非抽象成员;而接口所有的成员都是抽象的。
2、抽象成员可以私有,而接口的成员默认是共有的。
3、接口中不能包含构造函数、析构函数、静态成员、常量 、字段。
4、C# 只支持单继承,即一个子类只能继承一个父类,而一个子类却能够实现多个接口。
练习:
创建IArea 和IVolume接口,创建Ball 类实现这两个接口,并实现计算球面积area 和球体积volume.
IArea
using System;namespace TestInterFace{ public interface IArea { float R{ //半径的属性 get; set; } float Area(); //面积的方法 }}
IVolumeusing System;namespace TestInterFace{ public interface IVolume { float Volume();// 体积的方法 }}
Ballusing System;namespace TestInterFace{ public class Ball:IArea,IVolume { private float radius; //半径 public float R { get { return radius; } set{ radius = value; } } public float Area() { return (4.0f / 3.0f) * (float)Math.PI * radius * radius * radius; //Console.WriteLine("面积是 :{0}",area); } public float Volume() { return 4 * (float)Math.PI * radius * radius; //Console.WriteLine("体积是:{0}",volume); } public Ball() { } }}
Mainusing System;namespace TestInterFace{ class MainClass { public static void Main(string[] args) { Ball ball = new Ball(); ball.R = 4; float area=ball.Area(); float volume=ball.Volume(); Console.WriteLine("面积:{0},体积:{1}",area,volume); } }}
阅读全文
0 0
- C#接口Interface
- C#接口Interface
- C#接口Interface
- C#接口Interface
- C# interface 接口理解
- C# 接口使用 (interface)
- C#之接口(Interface)
- c# 接口interface 入门
- c# 接口 interface
- C# interface 接口理解
- C# Interface 接口
- C# 接口 interface
- C# 接口(Interface)
- C# 接口(Interface)
- C# interface(接口)
- 【C#学习】接口 Interface
- C#接口(Interface)
- C# 接口(Interface)
- 第一次用
- 一个人的旅行
- 文章标题
- AJAX增添用户时-检查用户名是否重复
- Sicily.1293 3n+1数链问题
- C# 接口(Interface)
- 【NOIP模板】 tarjan
- 贪婪策略
- 基于内容的视频检索(CBVR)
- Oracle数据库并行查询针对多核CPU
- 【牛客 题库】 深拷贝和浅拷贝
- 信息熵
- 框架的种子模块
- 算法--简单选择排序