1. 接口是一个引用类型,通过接口可以实现多重继承。
2. C#中接口不能有new、public、protected、internal、private等修饰符。
3. 接口中只能声明"抽象"成员(所以不能直接下一步对接口进行实例化(即不能使用new操作符声明一个接口的实例对 象)),而不能声明共有的域或者私有的成员变量。
4. 接口声明不包括数据成员,只能包含方法、属性、事件、索引等成员。
6. 接口成员的访问级别是默认的(默认为public),所以在声明时不能再为接口成员指定除public外的任何访问修饰符,否则 编译器会报错。
7. 接口成员不能有static、abstract、override、virtual修饰符,使用new修饰符不会报错,但会给出警告说不需要关键字new。
8. 在声明接口成员的时候,不准为接口成员编写具体的可执行代码,也就是说,只要在对接口进行声明时指明接口的成员名称和参数就可以了。
9. 接口一旦被继承,子类需要把接口中所有成员实例化(通过具体的可执行代码实现接口抽象成员的操作)
IBankAccount 接口
public interface IBankAccount
{
void PayIn(decimal amount);
bool Withdraw(decimal amount);
decimal Balance { get; }
}
Class1派生自IBankAccount
class Class1 : 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("Withdrawal 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);
}
}
Program类同样派生自IBankAccount接口,实现代码与Class1相同
class MainEntryPoint
{
static void Main()
{
IBankAccount ven = new Class1();
IBankAccount jup = new Program();
ven.PayIn(200);
ven.Withdraw(100);
Console.WriteLine(ven.ToString());
jup.PayIn(200);
jup.Withdraw(100);
Console.WriteLine(ven.ToString());
}