0

没有多重继承。但是我的项目伙伴使用接口来实现add, remove等方法。

这是代码:

public interface IAccountCategoryDataSource
{
    bool Add(AccountCategory accountCategory);
    bool Update(AccountCategory accountCategory);
    bool Remove(AccountCategory accountCategory);

    AccountCategory GetById(int id);
    AccountCategory GetByName(string name);
    IEnumerable<AccountCategory> GetByParentCategory(AccountCategory category);
    IEnumerable<AccountCategory> GetTopLevelCategories();
    IEnumerable<AccountCategory> GetBySearchTerm(string searchTerm);
    IEnumerable<AccountCategory> GetAll();

    event EventHandler<ObjectAddedEventArgs> AccountCategoryAdded;
    event EventHandler<ObjectUpdatedEventArgs> AccountCategoryUpdated;
    event EventHandler<ObjectRemovedEventArgs> AccountCategoryRemoved;
}

请解释接口的需要是什么。

4

1 回答 1

0

接口可用于多种用途。多重继承或解决循环引用很少。

但在大多数情况下,接口用于在消费者(需要某些功能的类)和实现(实现此功能的类)之间建立契约。这意味着,他们都同意这个功能是什么,但不同意这个功能将如何实现。消费者则不需要关心实现(消费者只是使用安排好的接口)并且实现者可以确定,当他正确实现接口的所有方法时,该接口的任何消费者都会接受该实现。这特别有用,如果消费者和实现类是由不同的人编写的,但即使不需要强调消费者不依赖特定实现这一事实,也可以使用它,这在面向对象中是非常好的实践编程。

举个例子,假设您正在研究具有从整数列表中返回 5 个最大整数的方法的类。最简单的方法是按降序对整个列表进行排序,然后返回前 5 个数字。但是你不想在你的类中实现排序算法,因为它是独立的功能,应该在其他类中实现(或者可能已经有类可以这样做)。因此,您使用一种方法Sort定义接口,该方法接受整数数组并返回排序数组。你不关心这个排序功能将如何实现,你只需要使用Sort这个接口的方法,即使你对排序算法一无所知,你也可以完成你的课程。然后您的同事(或您)将创建另一个实现此接口的类。他不需要知道任何关于你的类的事情,他可以使用任何他想要的排序算法,他可以在未来随时更改算法,它仍然可以一起工作。

接口必要性的一个很好的例子是插件。主应用程序的作者创建了具有功能的公开可用接口,他的应用程序将使用这些功能。然后,任何人编写具有此接口实现的类都可以将其用作插件。

于 2012-04-15T10:51:38.300 回答