接口与抽象类 [英] interface vs abstract class

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

问题描述


可能重复:

接口或抽象类?

我有一组定义的类如下:

I have a group of classes defined as follows:

namespace VGADevices.UsingAbstractClass
{
    public abstract class VGA
    {
        public abstract int HorizontalResolution { get; set; }
        public abstract int VerticalResolution { get; set; }
    }
    public class LCDScreen : VGA
    {
        public override int HorizontalResolution { get; set; }
        public override int VerticalResolution { get; set; }
    }
}  // namespace VGADevices.UsingAbstractClass

namespace VGADevices.UsingInterfaces
{
    public interface IVGA
    {
        int HorizontalResolution { get; set; }
        int VerticalResolution { get; set; }
    }
    public class LCDScreen : IVGA
    {
        public virtual int HorizontalResolution { get; set; }
        public virtual int VerticalResolution { get; set; }
    }
}  // namespace VGADevices.UsingInterfaces

客户端代码,I可以选择:

Client code, I have the choice between:

class Computer
{
        public VGA VGAOutput { get; set; }
}

class Computer
{
        public IVGA VGAOutput { get; set; }
}

我在某处读到使用接口更好,但为什么?
使用抽象类我可以定义一个接口以及添加数据成员,那么为什么接口是首选方法呢?
二元替换在这里也起作用吗?

I read somewhere that using interfaces is better, but why? With abstract classes I can define an interface as well plus add data-members so why are interfaces the preferred method? Does binary replacement play a role here as well?

谢谢

Chris

推荐答案

您可以继承(即实现)多个接口。您不能从多个抽象类继承

You can inherit from(that is, implement) multiple interfaces. You can't inherit from multiple abstract classes

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

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