简体   繁体   English

为什么接口变成抽象类 c#

[英]Why are interfaces turning into abstract classes c#

I'm honestly looking for good examples here of reasons to use interfaces over abstract.老实说,我在这里寻找很好的例子来说明使用接口而不是抽象的原因。 And the main reason I can see is they are unopinionated public blueprints for classes to follow.我能看到的主要原因是它们是供课程遵循的不拘一格的公共蓝图。 But with them adding default implementations thats no longer true.但是随着他们添加默认实现,情况就不再如此了。 Its becoming more and more difficult to distinguish interfaces from abstract classes.区分接口和抽象类变得越来越困难。 Genuinely whats the point in using an interface over an abstract class in c# 11. Its just a slower abstract class.在 c# 11 中使用抽象 class 接口的真正意义是什么。它只是一个较慢的抽象 class。

Even I find abstract classes and interfaces are too similar.甚至我都觉得抽象类和接口太相似了。 I prefer using abstract classes, as its methods can be defined, until and unless there's the concept of multiple inheritance used.我更喜欢使用抽象类,因为可以定义它的方法,直到并且除非使用了多个 inheritance 的概念。

As with case of abstract classes, we can't inherit from multiple abstract classes, whereas with interfaces, you could inherit as many interfaces you wish.与抽象类的情况一样,我们不能从多个抽象类继承,而对于接口,您可以继承任意数量的接口。

I'll let you understand this through a patch of code.我将通过一段代码让您了解这一点。

interface IFirstInterface
    {
        void myMethod();
    }
    interface ISecondInterface
    {
        void myOtherMethod();
    }
    class Democlass : IFirstInterface, ISecondInterface
    {
        public void myMethod()
        {
            System.Console.WriteLine("Some text..");
        }
        public void myOtherMethod()
        {
            System.Console.WriteLine("Some other text..");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Democlass myObj = new Democlass();
            myObj.myMethod();
            myObj.myOtherMethod();
        }
    }

Lemme know if you find this unclear.让我知道你是否觉得这不清楚。

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

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