接口语法上与声明抽象类完全相同,但是不允许提供接口中任何成员的实现方式。一般情况只能包含方法,属性,索引器,和事件声明,不能实例化。
实现接口:接口表示成员的存在性,类负责确定这些方法的实现代码,如果缺少实现代码,编译器会产生错误。
接口可以引用任何实现该接口的类。
源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InterfaceDemo2
{
#region 声明一个接口
public interface IBankAccount
{
void PayIn(decimal amount);
bool WithDraw(decimal amount);
decimal Balance { get; }
}
#endregion
#region 第1个类实现接口,即继承该接口
public class SaverAccount:IBankAccount
{
private decimal balance;
public void PayIn(decimal amount)
{
balance += amount;
}
public bool WithDraw(decimal amount)
{
if (balance >= amount )
{
balance -= amount;
return true;
}
Console.WriteLine("WithDraw Faileed!");
return false;
}
public decimal Balance
{
get
{
return balance;
}
}
public override string ToString()
{
return String.Format("Balance is :{0,6:C}", balance);
}
}
#endregion
#region 第2个类实现接口,即继承该接口
public class SaverAccount2: IBankAccount
{
private decimal balance;
public void PayIn(decimal amount)
{
balance += amount;
}
public bool WithDraw(decimal amount)
{
if (balance >= amount)
{
balance -= amount;
return true;
}
Console.WriteLine("WithDraw Faileed!");
return false;
}
public decimal Balance
{
get
{
return balance;
}
}
public override string ToString()
{
return String.Format("Balance is :{0,6:C}", balance);
}
}
#endregion
#region 派生的接口
public interface ITransferBankAccount :IBankAccount
{
//除了IBankAccount中的成员和方法外,新增TransferTo方法
bool TransferTo(IBankAccount destination, decimal amonut);
}
#endregion
#region 继承派生类
public class CurrentAccount:ITransferBankAccount
{
private decimal balance;
public void PayIn(decimal amount)
{
balance += amount;
}
public bool WithDraw(decimal amount)
{
if (balance >= amount)
{
balance -= amount;
return true;
}
Console.WriteLine("WithDraw Faileed!");
return false;
}
public decimal Balance
{
get
{
return balance;
}
}
public override string ToString()
{
return String.Format("Balance is :{0,6:C}", balance);
}
//新增加TransferTo实现函数
public bool TransferTo(IBankAccount destination,decimal amount)
{
bool result;
result = WithDraw(amount);
if (result )
{
destination.PayIn(amount);
}
return result;
}
}
#endregion
class Program
{
static void Main(string[] args)
{
IBankAccount Acconut1 = new SaverAccount(); //接口可以引用任何实现该接口的类
Acconut1.PayIn(200);
Acconut1.WithDraw(50);
// Acconut1.WithDraw(500);
Console.WriteLine("The Account1 Balance is {0}", Acconut1.Balance.ToString ());
//实现第2个类的方法
IBankAccount Account2 = new SaverAccount2();
Account2.PayIn(1000);
Account2.WithDraw(1200);
Account2.PayIn(100);
Console.WriteLine("The Account2 Balance is {0}", Account2.Balance.ToString ());
//派生接口,类的实现
ITransferBankAccount ACT = new CurrentAccount();
ACT.PayIn(500);
ACT.TransferTo(Acconut1, 200); //转到第一个账户上
Console.WriteLine("The first Account Banlace is {0:6:C}", Acconut1.Balance.ToString());
Console.WriteLine("The Current Account Banlace is {0:6:C}", ACT.Balance.ToString());
Console.Read();
}
}
}