C# 中的继承与接口 [英] Inheritance vs. interface in C#

查看:27
本文介绍了C# 中的继承与接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
接口与基类
我应该什么时候选择继承而不是设计 C# 类库时的接口?

所以我正在用 C# 编写我的第一个真正的程序.该程序将从四个不同的网站抓取数据.我的计划是让一个父类看起来像这样:

So I'm writing my first real program in C#. The program will scrape data from four different websites. My plan is to have one parent class that will look like this:

class Scraper
{
    string scrapeDate(url);
    string scrapeTime(url);
    //&c.
}

然后我将有四个类继承它.

Then I will have four classes that inherit from it.

另一种选择是使 Scraper 成为一个接口并有四个类来实现它.

The other option is to make Scraper an interface and have four classes implementing it.

这些方法之间有什么区别?

What are the differences between these approaches?

推荐答案

类继承代表了一种is-a"关系,例如,一个Tank就是一个Vehicle.如果您的情况至少不满足这一点,请选择接口而不是继承.

Class inheritance represents an "is-a" relationship, e.g., a Tank is a Vehicle. If your situation doesn't at least meet this, choose interface over inheritance.

如果提议的基类没有为您的方法提供默认实现,这将是选择接口而不是继承的另一个原因.

If the proposed base class doesn't provide default implementations for your methods, this would be another reason to choose interface over inheritance.

在C#中,你只能从一个类继承多个接口.这将是选择接口而不是继承的另一个原因.

In C#, you can only inherit from one class but multiple interfaces. This would be yet another reason to choose interface over inheritance.

明白了吗?

这篇关于C# 中的继承与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆