Why do both the abstract class and interface exist in C#?

前端 未结 11 1937
渐次进展
渐次进展 2020-12-03 00:00

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.

Is it because:

11条回答
  •  春和景丽
    2020-12-03 00:46

    An interface is used for what a class can do, but it is also used to hide some of things that a class can do.

    For example the IEnumerable interface describes that a class can iterate through it's members, but it's also limits the access to this single ability. A List can also access the items by index, but when you access it through the IEnumerable interface, you only know about it's ability to iterate the members.

    If a method accepts the IEnumerable interface as a parameter, that means that it's only interrested in the ability to iterate through the members. You can use several different classes with this ability (like a List or an array T[]) without the need for one method for each class.

    Not only can a method accept several different classes that implement an interface, you can create new classes that implement the interface and the method will happily accept those too.

提交回复
热议问题