接口可以继承接口,其方式与类的继承方式相同。 下面通过定义一个新的 ITransferBankAccount 接口来说明这个概念,该接口的功能与 IBankAccount 相同, 只是又定义了一个方法,把资金直接转到另一个账户上:
public interface ITransferBankAccount : IBankAccount
{
bool TransferTo(IBankAccount destination, decimal amount);
}
因为 ITransferBankAccount 派生自 IBankAccount, 所以它拥有 IBankAccount的所有成员和它自己的成员。如果自定义类继承了ITransferBankAccount接口就必须要实现 IBankAccount的所有方法和 ITransferBankAccount中定义的方法。 如果没有实现就会产生一个编译错误。
注意, TransferTo() 方法对于目标账户使用 IBankAccount 接口引用。 这说明了接口的用途:在实现并调用这个方法时,不必知道转账的对象类型, 只需要知道该对象实现 IBankAccount 即可。
下面代码为了更简洁,所以我只演示实现 TransferTo 方法的实现, 其他的如果不清楚可以看我前面写的 C#接口小实例这一章
public class CurrentAccount : ITransferBankAccount
{
public bool TransferTo(IBankAccount destination, decimal amount)
{
bool result = this.Withdraw(amount);
if(result)
{
destination.PlayIn(amount);
}
return result;
}
}
可以用下面的代码验证该类:
static void Main()
{
IBankAccount venusAccount = new SaverAccount();
ITransferBankAccount jupiterAccount = new CurrentAccount();
venusAccount.PayIn(200);
jupiterAccount.PlayIn(500);
jupiterAccount.TransferTo(venusAccount, 100);
Console.WriteLine(venusAccount.ToString());
Console.WriteLine(jupiterAccount.ToString());
}