


Detailed explanation of abstract classes and interfaces in C#
Problems arise:
When we use C# abstract classes and interfaces, we often encounter the following similar problems, which are roughly summarized as follows:
( 1) What are the essential differences and connections between abstract classes and interfaces?
(2) When should you choose to use abstract classes, and when is it most appropriate to use interfaces?
(3) How to use it in the project to make the project more maintainable and scalable? How to combine it closely with Struct and classes to achieve the ultimate double-edged sword effect?
Solution:
#This is also a problem I encountered when learning abstract classes and interfaces. From what I summarized From these three questions, it is not difficult to see that these may be the three stages where most of our programmers encounter problems,
The first stage (basic concepts): Just like question 1, These people first need to clear the obstacles of basic concepts. First, they must understand what abstract classes are and what interfaces are.
Then understand what are the differences and connections between abstract classes and interfaces? Of course, this may take some time to understand and practice. After all, these concepts are relatively abstract and cannot be touched or seen. Of course, the most important thing is to practice more. When you have nothing to do, make a Demo instance and use them all. When using it, think more about why you need to use it this way? What are the benefits of this? Can interfaces be used? If not, what are the benefits of using abstract classes? This can deepen your understanding of them. This is also my little experience, haha! Having said so much, let me summarize question 1. First, it is convenient for me to remember, and second, it is to deepen my understanding.
Concepts of abstract classes and interfaces: In fact, there are basically a lot of these concepts in textbooks and blogs. The seniors have summarized them very well, but they may be a bit obscure and difficult to understand in terms of popularity and ease of understanding. I Just translate it and add some Shaanxi vernacular, hehe.
(1) Abstract class: Provides a set of public methods for derived classes to access shared base classes;
The characteristics of abstract classes are: (1) Abstract classes include both abstract methods and Including the implementation of methods; (2) Abstract classes cannot be instantiated or sealed; (3) Abstract methods in abstract classes must either be implemented in derived classes or inherited by derived abstract classes (abstract derived classes can inherit base classes abstract method), if you want to implement the abstract method of the base class in a derived class, you must use the override modifier; (4) Abstract classes belong to single inheritance (this belongs to the same nature of all classes, mention it here) (5) Abstract A class is a group of abstractions, similar to IS-A;
If what I said above is not clear enough, I will give you the address of the official website about abstract classes: https://docs.microsoft.com/ en-us/dotnet/csharp/language-reference/keywords/abstract
(2) Interface: an abstract type that contains a set of virtual methods; the characteristics of the
interface are: (1) The interface only includes the definition of virtual methods, only declaration definitions, and no function implementations; (2) Interface classes can include properties, events, indexers, etc., but not fields; (3) Interface classes belong to multiple inheritance; (4) Classes that inherit an interface must implement all methods of the interface;
The difference and connection between abstract classes and interfaces:
The same points: (1) They cannot be instantiated directly, only It can be realized through inheritance;
(2) They are all abstractions of things’ behaviors and objects, forming a certain design pattern;
Differences:
(1) Interfaces support multiple inheritance; abstract classes cannot implement multiple inheritance;
(2) Interfaces include methods, properties, events, and indexers, but cannot include fields; abstract classes can include fields and method implementations;
(3) Interfaces can support callbacks, abstract classes do not support callbacks
(4) Interfaces can be used as base classes for value types and reference types, while abstract classes can only be used as base classes for reference types;
The second stage (use stage): Just like question 2, these people have a certain understanding of the basics, but they lack some practice. Maybe they just make a simple Demo. , so when to use abstract classes and when to use interfaces?
Analyzing the second question, I put forward three suggestions:
The first suggestion is that the basic concepts are not just memorization of concepts, but should be practiced and thought more, and then Practice more, think more, repeat it several times until you are familiar with it;
The second suggestion is to try to use this knowledge in your own projects. Only by using it can you find problems and solve them. Only when you think about problems can you think;
The third suggestion is to summarize and summarize the knowledge points of the abstract classes and interface projects that you have used;
In terms of when to use abstract classes and interfaces, I summarize The following points are given based on the experience of seniors, for reference only:
(1) When the designed component will have multiple versions in the future, abstract classes are generally used. For example, using C# to design a database DB. At the beginning, you may use sql server, mysql. In the future, large projects may need to use oracle. For a large database system like DB, when we design the class, we design an abstract base class DB, so that it has some common attributes and methods of data. Attributes: database connection name, version, database type, database Common methods: Open(), Close() methods, etc.;
(2) When the designed components also support common behaviors, interfaces can be considered; for example, birds, humans, and cars can all have sounds. At this time, you can design the interface, including the called function behavior, and then implement it in each specific class;
(3) In the derived class or interface that inherits the interface, once the interface needs to add behavioral methods, it is a comparison The headache is that all inheritance must implement its methods. At this time, you can implement a new interface in the derived class to realize the unique actions of the derived class. For example:
/// <summary> /// 实现一个爬行动物的动作接口 /// </summary> interface IAnimalClimb { void Climb(); } /// <summary> /// 实现一个会叫的动物的动作接口 /// </summary> interface ICry { void Cry(); } /// <summary> /// 实现一个动物抽象类 /// </summary> public abstract class Animal { //动物的名字 public string Name { get; set; } //动物的颜色 public string Color { get; set; } //动物抽象类的共有方法 public abstract void Sleep(); public abstract void Breathe(); } /// <summary> /// 定义鸟类,通用方法是会飞 /// </summary> public class Bird : Animal,ICry { public override void Sleep() { Console.WriteLine("Bird派生类继承了基类的Sleep()方法"); } public override void Breathe() { Console.WriteLine("Bird派生类继承了基类的Breathe()方法"); } //鸟类可以继承统一的接口动作,例如:叫 public void Cry() { Console.WriteLine("Bird派生类继承了接口ICry的叫的方法"); } } /// <summary> /// 定义爬行动物类 /// </summary> public class Snake : Animal, IAnimalClimb { public override void Breathe() { Console.WriteLine("Snake派生类继承了基类的Sleep()方法"); } public override void Sleep() { Console.WriteLine("Snake派生类继承了基类的Sleep()方法"); } //爬行动物可以继承统一的接口动物,例如:爬 public void Climb() { Console.WriteLine("Snake派生类继承了接口IAnimalClimb的爬的方法"); } }
The above code, Just to illustrate the problem, it is relatively simple;
The third stage (optimization stage): Just like question 3, when we make an abstract class or interface, the first thing we consider is that it can be used, and the result is the defined class Or there are many interfaces, which are difficult to maintain and extend, or there are intersections between classes. How to optimize the inheritance relationship? How can we make the program maintainable and scalable?
I personally recommend that you have the following aspects:
(1) You must have solid basic knowledge and deep basic skills;
(2) You must have a person who asks more questions and thinks more. Be careful; ask more about abstract classes and interfaces, why not use abstract classes but use interfaces? Why is it appropriate to use an interface in this place?
(3) Take a look at how the seniors design interfaces and classes. There is a lot of information in this area available online;
(4) I personally recommend reading more about design patterns, because they are Experience and thoughts of seniors in design;
The above is the detailed content of Detailed explanation of abstract classes and interfaces in C#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Numpy is a Python scientific computing library that provides a wealth of array operation functions and tools. When upgrading the Numpy version, you need to query the current version to ensure compatibility. This article will introduce the method of Numpy version query in detail and provide specific code examples. Method 1: Use Python code to query the Numpy version. You can easily query the Numpy version using Python code. The following is the implementation method and sample code: importnumpyasnpprint(np
