简体   繁体   English

本例中的接口和抽象类

[英]Interface and abstract class in this case

In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface.如果我希望任何类继承/实现一些方法,这些方法是更好的接口或抽象类仅包含这些抽象方法并充当接口。 I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something?我很清楚接口和抽象类之间的区别,但在这种情况下,两者是否具有相同的功能或不同的东西?

I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface.我认为我们可以随意使用其中一个,但我仍然站在接口一边,因为我的目标是强制任何类实现这些方法,这是接口的工作。

I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface.我同意一个没有具体行为的抽象类似乎有点毫无意义,所以我更喜欢一个接口。

Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods当将一些不能被覆盖的常见行为与一些可以例如模板方法的元素结合在一起时,抽象类更有用

public abstract class Base
{
    public void TemplateMethod()
    {
        AbstractMethod1();
        AbstractMethod2();
    }

    public abstract void AbstractMethod1();
    public abstract void AbstractMethod2();
}


public class Concrete : Base
{
    public override void AbstractMethod1()
    {
        Console.Write("Override Abstract Method 1");
    }

    public override void AbstractMethod2()
    {
        Console.Write("Override Abstract Method 2");
    }
}

public class Main
{
    public Main()
    {
        var concrete = new Concrete();
        concrete.TemplateMethod();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM