C# 教程
- 第1节:C# 简介
- 第2节:C# 环境
- 第3节:C# 程序结构
- 第4节:C# 基本语法
- 第5节:C# 数据类型
- 第6节:C# 类型转换
- 第7节:C# 变量
- 第8节:C# 常量
- 第9节:C# 运算符
- 第10节:C# 判断
- 第11节:C# 循环
- 第12节:C# 封装
- 第13节:C# 方法
- 第14节:C# 可空类型(Nullable)
- 第15节:C# 数组(Array)
- 第16节:C# 字符串(String)
- 第17节:C# 结构(Struct)
- 第18节:C# 枚举(Enum)
- 第19节:C# 类(Class)
- 第20节:C# 继承
- 第21节:C# 多态性
- 第22节:C# 运算符重载
- 第23节:C# 接口(Interface)
- 第24节:C# 命名空间(Namespace)
- 第25节:C# 预处理器指令
- 第26节:C# 正则表达式
- 第27节:C# 异常处理
- 第28节:C# 文件的输入与输出
- 第29节:C# 特性(Attribute)
- 第30节:C# 反射(Reflection)
- 第31节:C# 属性(Property)
- 第32节:C# 索引器(Indexer)
- 第33节:C# 委托(Delegate)
- 第34节:C# 事件(Event)
- 第35节:C# 集合(Collection)
- 第36节:C# 泛型(Generic)
- 第37节:C# 匿名方法
- 第38节:C# 不安全代码
- 第39节:C# 多线程
C# 接口(Interface)
接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同 "是什么" 部分,派生类定义了语法合同 "怎么做" 部分。
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。
抽象类在某种程度上与接口类似,但是,它们大多只是用在当只有少数方法由基类声明由派生类实现时。
声明接口
接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例:
interface ITransactions{
// 接口成员
void showTransaction();
double getAmount();
}
实例
下面的实例演示了上面接口的实现:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication{
interface ITransactions{
// 接口成员
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions{
private string tCode;
private string date;
private double amount;
public Transaction(){
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a){
tCode = c;
date = d;
amount = a;
}
public double getAmount(){
return amount;
}
public void showTransaction(){
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester{
static void Main(string[] args){
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
接口使用的注意事项:
- 接口方法不能用public abstract等修饰。接口内不能有字段变量,构造函数。
- 接口内可以定义属性(有get和set的方法)。如string color { get ; set ; }这种。
- 实现接口时,必须和接口的格式一致。
- 必须实现接口的所有方法。