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

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

问题描述

可能的重复:
接口还是抽象类?

我有一组定义如下:

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

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

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?

谢谢

克里斯

推荐答案

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

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

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

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