声明接口在语法上与声明抽象类完全相同,但不允许提供接口中任何成员的实现方式。 一般情况下,接口只能包含方法、属性、索引器和事件的声明。不能实例化接口 ,它只能包含其成员的 签名。接口既不能有构造函数,接口定义也不允许包含运算符重载。
6.1 定义和实现接口
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 定义接口{ public interface IBankAccount { void PayIn(decimal amount); bool Withdraw(decimal amount); decimal Balance { get; } } class Program { static void Main(string[] args) { IBankAccount x = new SaveAccount(); IBankAccount y = new SaveAccount(); x.PayIn(200); x.Withdraw(100); Console.WriteLine(x.ToString()); y.PayIn(500); y.Withdraw(600); y.Withdraw(100); Console.WriteLine(y.ToString()); } }}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 定义接口{ public class SaveAccount : IBankAccount { private decimal balance; public void PayIn(decimal amount) { balance+= amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } else { Console.WriteLine("Withdraw1 attempt failed"); return false; } } public decimal Balance { get { return balance; } } public override string ToString() { return String.Format("Venus Bank Saver:Balance={0,6:C}", balance); } }}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 定义接口{ public class GoldAccount : IBankAccount { private decimal balance; public void PayIn(decimal amount) { balance += amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } else { Console.WriteLine("Withdraw1 attempt failed"); return false; } } public decimal Balance { get { return balance; } } public override string ToString() { return String.Format("Venus Bank Saver:Balance={0,6:C}", balance); } }}