search
HomeBackend DevelopmentC#.Net TutorialIntroduction to the difference between interfaces and classes in .NET

Interfaces and classes are often used in our daily development. What is the difference between the two? What are the advantages and disadvantages? The following article will introduce to you relevant information about the difference between interfaces and classes in .NET. Friends who need it can refer to it. Let's take a look together.

Preface

Everyone should know that .Net provides an interface, which is different from the type definition of Class or Struct. In some cases, interfaces seem to be the same as abstract classes, so some people think that abstract classes can be completely replaced by interfaces in .Net. In fact, this is not the case. Interfaces and abstract classes each have their own strengths and weaknesses, so they are often used in combination in applications to complement each other. Not much to say below, let’s take a look at the detailed introduction.

Next, let’s talk about the difference between abstract classes and interfaces:

The difference is that the concepts expressed by the two are different. Abstract class is a high degree of aggregation of a class of things, so for subclasses that inherit abstract classes, it is a "yes" relationship for abstract classes; interfaces define behavioral specifications, so for subclasses that implement interfaces , relative to the interface, it is "the behavior needs to be completed according to the interface." This may sound a bit false, but here’s an example. For example, dog is a general term for all canine animals, Pekingese is dog, and Shepherd is dog. Then the general characteristics of dogs will be found in Pekingese and Shepherd. So compared to Pekingese and Shepherd, dog is It belongs to the abstract type of this kind of thing; and for the action of "barking", dogs can bark and birds can also bark. Obviously, the former is equivalent to the abstract class, while the latter refers to the interface.

Difference 2: When an abstract class defines a type method, the implementation part of the method may or may not be given; but for an interface, the implementation part cannot be given for any method defined in it.

For example:


publicabstractclassAbsTest
{
publicvirtualvoidTest()
{
Debug.WriteLine("Test");
}
publicabstractvoidNewTest();
}
publicinterfaceITest
{
voidTest();
voidNewTest();
}

Difference three, inheritance classes have different implementations of the methods involved in the two. The inherited class does not need to rewrite the abstract methods defined by the abstract class, that is to say, the methods of the abstract class can be extended; for the methods or attributes defined by the interface class, the corresponding methods must be given in the inherited class. The methods and properties are implemented.

Difference 4: In an abstract class, if a new method is added, it does not need to be used for any processing in the inherited class; but for interfaces, the inherited class needs to be modified to provide a newly defined method.

Now that we know the difference between the two, let’s talk about the advantages of interfaces over abstract classes.

Benefits 1: Interfaces can not only act on reference types, but also on value types. As for abstract classes, they can only act on reference types.

Benefit 2: .Net type inheritance can only be single inheritance, which means that a type can only inherit one type, but can inherit multiple interfaces. In fact, I agree with this point. Multiple inheritance will make the inheritance tree confusing.

Benefit 3: Since the interface only defines properties and methods and has little to do with the actual implemented type, the interface can be reused by multiple types. In contrast, the relationship between abstract classes and inherited classes is closer.

Benefit 4: Through interfaces, the attributes and methods exposed by a type can be reduced, thereby making it easier to protect type objects. When a type that implements an interface may contain other methods or attributes, but when the method returns, it can return the interface object. In this way, the calling end can only access the relevant elements of the object through the methods or attributes provided by the interface, which can effectively protect the object. other elements.

Benefit 5: Reduce the unboxing operations of value types. For value type data defined by Struct, when it is stored in a collection, it needs to be unboxed every time it is taken out. In this case, the method of combining Struct+Interface is used to reduce the unboxing operation.

Compared to abstract classes, interfaces have so many benefits, but interfaces have a fatal weakness, that is, the methods and properties defined by the interface can only be relative to the type that inherits it (unless modified in the inherited class) function label defined by the interface), then when it comes to multi-layer inheritance relationships, it is difficult to implement it using interfaces alone. Because if each type inherits the interface and implements it, not to mention that writing code is more cumbersome, and sometimes the execution result is wrong, especially when the subtype object is implicitly converted into a base class object for access.

At this time, it needs to be implemented using interfaces combined with virtual methods. In fact, in inheritance, should we use interfaces or abstract classes? The interface is fixed and conventional, so the implementation of the corresponding methods and properties of the interface must be provided in the inherited class. For abstract classes, the implementation of the definition method of the abstract class runs through the entire inheritance tree, so the implementation or rewriting of the methods is uncertain. Therefore, relatively speaking, abstract classes are more flexible than interfaces.

A simple comparison table between the two is given below.


Interface

Abstract class

Multiple inheritance

Supported

Not supported

Type restrictions

No

Yes, it can only be a reference type

method implementation

The method implementation must be given in the inherited type

It does not need to be given in the inherited class

Extensibility

More troublesome

Relatively flexible

Multi-layer inheritance

It’s more troublesome, you need to use virtual functions

It’s more flexible

In general, interfaces and abstract classes are language means provided by .Net to better realize the inheritance relationship between types, and the two are somewhat complementary to each other. Therefore, I do not emphasize what to use and what not to use. The key to the problem is how to apply these two methods reasonably to the program. This is crucial.

Summarize

The above is the detailed content of Introduction to the difference between interfaces and classes in .NET. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
区分win11商务版和消费者版的区别区分win11商务版和消费者版的区别Jan 05, 2024 pm 04:53 PM

win11business和consumer版本其实就是消费版还有商业版,两者的区别不大,但还是有的,下面我们就一起来看一下两者的具体区别在哪里。win11business和consumer版本区别:1、两者如果版本相同的话,跟专业版没什么区别。2、两者的功能基本相同,不过微软的授权方式是不同的。3、激活的方式也是不同的,consumer是单一授权,而business是批量授权。4、我们下载consumer就可以了。

华为GT3 Pro和GT4的差异是什么?华为GT3 Pro和GT4的差异是什么?Dec 29, 2023 pm 02:27 PM

许多用户在选择智能手表的时候都会选择的华为的品牌,其中华为GT3pro和GT4都是非常热门的选择,不少用户都很好奇华为GT3pro和GT4有什么区别,下面就就给大家介绍一下二者。华为GT3pro和GT4有什么区别一、外观GT4:46mm和41mm,材质是玻璃表镜+不锈钢机身+高分纤维后壳。GT3pro:46.6mm和42.9mm,材质是蓝宝石玻璃表镜+钛金属机身/陶瓷机身+陶瓷后壳二、健康GT4:采用最新的华为Truseen5.5+算法,结果会更加的精准。GT3pro:多了ECG心电图和血管及安

在C语言中,while(1)和while(0)之间的区别是什么?在C语言中,while(1)和while(0)之间的区别是什么?Aug 31, 2023 am 10:45 AM

我们知道在C语言中,'while'关键字用于定义一个循环,该循环根据传递给循环的条件来工作。现在,由于条件可以有两个值,即真或假,所以如果条件为真,则while块内的代码将被重复执行,如果条件为假,则代码将不会被执行。现在,通过将参数传递给while循环,我们可以区分while(1)和while(0),因为while(1)是一个条件始终被视为真的循环,因此块内的代码将开始重复执行。此外,我们可以说明,传递给循环并使条件为真的不是1,而是如果任何非零整数传递给while循环,则它将被视为真条件,因

win10逻辑分区和主分区的区别win10逻辑分区和主分区的区别Jan 03, 2024 pm 04:17 PM

最近不少小伙伴问小编,win10逻辑分区和主分区的区别是什么,我们大多数电脑,其实都是分为了一个C盘主分区,然后其他的D盘、E盘和F盘等都属于逻辑分区,一般情况下是→然后再建→在扩展分区里面,再创建。下面小编整理了详细的教程,一起来看看吧。win10逻辑分区和主分区区别的详细介绍主分区、扩展分区和逻辑分区的区别简单来说,我们大多数电脑,都是分为了一个C盘主分区,然后其他的D盘、E盘和F盘等都属于逻辑分区,将D盘、E盘、F盘等出了主分区之外的磁盘组合,则就属于一个扩展分区。对于硬盘主分区、扩展分区

win32和win64有什么区别win32和win64有什么区别May 29, 2023 pm 05:22 PM

win32和win64的区别是:1、win32是指Microsoft Windows操作系统的32位环境,win64是指Microsoft Windows操作系统的64位版本,比32位版本更加稳定快速;2、win32最高支持2G的内存,win64必须是4G以上内存;3、win64支持基于64位的处理器,而win32却不能完全支持;4、win32追求简洁,win64追求性能。

分享几个.NET开源的AI和LLM相关项目框架分享几个.NET开源的AI和LLM相关项目框架May 06, 2024 pm 04:43 PM

当今人工智能(AI)技术的发展如火如荼,它们在各个领域都展现出了巨大的潜力和影响力。今天大姚给大家分享4个.NET开源的AI模型LLM相关的项目框架,希望能为大家提供一些参考。https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一种开源的软件开发工具包(SDK),旨在将大型语言模型(LLM)如OpenAI、Azure

在C语言中,结构体(Structure)和数组(Array)之间的区别是什么?在C语言中,结构体(Structure)和数组(Array)之间的区别是什么?Aug 30, 2023 pm 09:37 PM

在C中,结构体和数组都用作数据类型的容器,即在结构体和数组中我们都可以存储数据,也可以对它们执行不同的操作。基于内部实现,以下是两者之间存在一些基本差异。Sr.编号键结构数组1定义结构体可以定义为一种数据结构,用作容器,可以容纳不同类型的变量。另一方面,数组是一种用作容器的数据结构,可以容纳相同类型的变量,但不支持多种数据类型变量。2内存分配输入数据的内存分配结构不必位于连续的内存位置。而在数组的情况下,输入数据存储在连续的内存分配中,这意味着数组将数据存储在分配连续内存块的内存模型中(即,具有

C#的就业前景如何C#的就业前景如何Oct 19, 2023 am 11:02 AM

无论您是初学者还是有经验的专业人士,掌握C#将为您的职业发展铺平道路。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.