C#高级编程笔记 Day 4, 2016年9月 12日(接口)

1、定义和实现接口:接口名称通常上以字母 I 开头

  例子:定义IBankAccount接口

1 namespace Test.YinXi{
2     public interface IBankAccount{
3         void PayIn(decimal amount);
4         bool Withdraw(decimal amount);
5         decimal Balance{
6             get;
7         }
8     }
9 }

  下面是一个实现了 IBankAccount 接口的类

 1 namespace Test.Yinxi.Bank{
 2     public class SaverAccount:IBankAccount{
 3         private decimal balance;
 4         public void PayIn(decimal amount){
 5             balance+=amount;
 6         }
 7         public bool Withdraw(decimal amount){
 8             if(balance>=amount){
 9                 balance-=amount;
10                 return true;
11             }
12             Console.WriteLine("Withdrawal attempt failed.");
13             return false;
14          }
15         public decimal Balance{
16             get{
17                 return balance;
18             }
19         }
20         public override string ToString(){
21             return String.Format("Bank Saver: Balance={0,6:C}",balance);
22         }
23     }
24 }

  SaverAccount 派生自IBankAccount ,表示它获得了IBankAccount 的所有成员,但接口实际上并不实现其方法,所以SaverAccount必须提供这些方法的所有实现代码。如果缺少实现代码,编译器就会产生错误。接口仅表示其成员的存在性,类负责确定这些成员是虚拟的还是抽象的(但只有在类本身是抽象的,这些函数才能是抽象的)

  在本例中,接口的任何函数不必是虚拟的。

  接下来是一个测试代码:用来测试上面写的实现的接口

  

 1 using System;
 2 using Test.YinXi;
 3 using Test.YinXi.Bank;
 4 
 5 namespace Test.Yinxi
 6 {
 7     class MainEntryPoint
 8     {
 9         public static void Main(string[] args)
10         {
11             IBankAccount bank=new SaverAccount();
12             bank.PayIn(1000);
13             bank.Withdraw(200);
14             Console.WriteLine(bank.ToString());
15         }
16     }
17 }    

2、派生的接口

  接口可以彼此继承,其方式与类的继承方式相同。下面是定义一个新的接口 ITransferBankAccount 继承 IBankAccount

  

1 namespace Test.YinXi
2 {
3     public interface ITransferBankAccount :IBankAccount
4     {
5         bool TransferTo(IBankAccount destination,decimal amount);
6     }
7 }

  因为ITranssferBankAccount 派生自 IBankAccount ,所以它拥有IBank'Account 的所有成员和它自己的成员。这表示实现(派生自)ITransferBankAccount 的任何类都必须实现IBankAccount 的所有方法和在ITransferBankAccount 中定义的新方法 TransferTo()。

原文地址:https://www.cnblogs.com/xiyin/p/5863732.html