abstract class and interface in C# look like much, but sometimes they get the similiar use. However, there are still much differences between them. here we go.
抽象类和接口初看上去很象,但是还是有很多区别的。
a) Interface Grammar接口语法
[public|protected|internal|private] interface interfaceName
{
public int add(int x,int y);
//this is error! interface memeber can not be described with any characters to declare its access attribute.
//接口中任何成员和属性不能被任何修饰符修饰来表明其访问属性!
int add(int x,int y);
//this is right!
int Count{get;} //interface property接口属性
string this[int index]{get;set;}//index interface 接口索引
}
Difference:
1. in interface, all interface members can not be decorated with any other access tag,such as public,private.etc.
2. in abtract class, such case is just on the opposite.
b) abstract class Grammar 抽象类语法
[public|protected|internal|private] abstct class className
{
public abstract int add(int x,int y);
//it's ok, but that forbidden in interface!
//在abstract class中,类成员可以有各种修饰符。如果该类成员没有被implement,那么该类一定要被标示为abstact方法。否则出错!当然也可以实现该方法。如下multiply方法所示
public virtual int multiply(int x,int y)
{
return x*y;
}
}
Difference:
1.in interface, all interface memebers can not be implemented. and it's just an declaration for other class which will inherented from it and implemented all of them.
在接口中,所有接口成员都不能被实现,它只是一个申明而已,其他类继承自该接口,并且要实现该接口中的所有成员。
2 in abstract class, its member can be implemented ,otherwise must be decorated with abstract that is the same with interface . of course, any class inherented from this must implemented all its abstract method. of course, u can also override the method that has already implemented method.
在抽象类中,其成员可以被实现,如果不实现的话,其方法成员一定要被标标示为abstract. 同时,任何继承于该抽象类的类必须要实现其所有标示为abstract的方法,这点与interface相同。或者该类也可以override该抽象类中的method. 这一点interface绝对不可能,因为interface中根本没有实现过,何来override?
转载于:https://www.cnblogs.com/Winston/archive/2008/04/23/1166876.html