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

发布于 2025-01-21 23:06:10 字数 142 浏览 3 评论 0原文

老实说,我在这里寻找很好的例子,这些理由是使用抽象的接口。我能看到的主要原因是它们是未开放的公共蓝图,供课程遵循。但是随着他们添加默认实现,这不再是正确的。将界面与抽象类别区分开来变得越来越困难。真正地,在C#11中使用摘要类上的界面是什么意义。它只是一个较慢的抽象类。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流绪微梦 2025-01-28 23:06:10

甚至我发现抽象类和接口太相似。我更喜欢使用抽象类,因为可以定义其方法,直到使用了多个继承的概念。

与抽象类的情况一样,我们不能从多个抽象类中继承,而使用接口,您可以继承所需的尽可能多的接口。

我会让您通过一组代码理解这一点。

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知道您是否觉得这不清楚。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文