接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同 "是什么" 部分,派生类定义了语法合同 "怎么做" 部分。
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。
抽象类在某种程度上与接口类似,但是,它们大多只是用在当只有少数方法由基类声明由派生类实现时。
接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例:
public interface ITransactions |
{ |
// 接口成员 |
void showTransaction(); |
double getAmount(); |
} |
下面的实例演示了上面接口的实现:
using System.Collections.Generic; |
using System.Linq; |
using System.Text; |
using System; |
namespace InterfaceApplication |
{ |
public interface ITransactions |
{ |
// interface members |
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 |