This article is a mirror article of machine translation, please click here to jump to the original article.

View: 18805|Reply: 0

[Communication] The similarities and differences between virtual and (abstract) abstracth and interface in C#...

[Copy link]
Posted on 4/22/2019 2:41:09 PM | | |
Interpretation 1

In C#, Abstract and Virtual are confusing, both related to inheritance, and involve the use of override. Let's discuss the differences between the two:

1. Virtual method

virtual keyword is used to modify methods in the base class. There are two situations where virtual is used:

Scenario 1: A virtual method is defined in the base class, but the virtual method is not rewritten in the derived class. In the call to the derived class instance, the virtual method uses the method defined by the base class.

Scenario 2: A virtual method is defined in the base class and then the method is rewritten using override in the derived class. In the call to the derived class instance, the virtual method uses the derived rewrite method.

2. Abstract method (abstract method)

The abstract keyword can only be used in abstract classes to modify methods, and there is no specific implementation. The implementation of abstract methods must be implemented using the override keyword in the derived class.

The most essential difference between an interface and an abstract class: an abstract class is an incomplete class, an abstraction of an object, while an interface is a behavioral norm.


3. Keywords

Static: When a method is declared as Static, the method is a static method and the compiler keeps the implementation of the method at compile time. That is, the method belongs to a class, but not to any member, regardless of whether an instance of the class exists or not. Just like the entry function Static void Main, because it is a static function, it can be called directly.

Virtua: When a method is declared as Virtual, it is a virtual method until you use ClassName variable = new ClassName(); Before declaring an instance of a class, it does not exist in real memory space. This keyword is very commonly used in class inheritance to provide polymorphism support for class methods.

overrride: indicates a rewrite This class inherits from the Shape class
virtual, abstract is to tell other classes that want to inherit from him that you can override this method or property of mine, otherwise it is not allowed.
abstract: abstract method declaration is a method that must be overridden by a derived class, which is used to be inherited; It can be regarded as an imaginary method without an realization; If a class contains an abstract method, then the class must be defined as an abstract class, whether or not it contains other general methods; Abstract classes cannot have substances.

a) The method of the virtual modification must have a method implementation (even if it is only a pair of braces), and the method of the abstract modification cannot have an implementation.

b) virtual can be rewritten by subclasses, abstract must be rewritten by subclasses

c) If a function in a class is modified by abstact, the class name must also be modified with abstact

d) Abstract modified classes cannot be created instances.

e) If a method in C# is prepared to rewrite the parent class in the subclass, the method must be modified with virtual in the parent class and overide in the subclass, avoiding the programmer accidentally rewriting the parent method of the parent class in the subclass.

Note: Classes modified with abstract can only be inherited, not instantiated.

Interpretation 2

Both virtual and abstract are used to modify the parent class, allowing the child class to be redefined by overriding the definition of the parent class.

They have one thing in common: if they are used to modify methods, public must be added in front of them, otherwise there will be compilation errors: virtual methods or abstract methods cannot be private. After all, adding virtual or abstract allows the subclass to be redefined, and private members cannot be accessed by the subclass.

But they are very different. (virtual is "virtual", abstract is "abstract").

(1) The method of virtual modification must be implemented (even if it only adds a pair of braces), while the method of abstract modification must not be implemented. For example, if the method of virtual modification is not implemented:

Error: "Test1.fun1()" must declare the body because it is not marked as abstract, extern, or partial   

For abstract modifiers, if implemented:


Error: "Test2.fun2()" cannot declare the body because it is marked as abstract   

(2) virtual can be rewritten by subclasses, while abstract must be rewritten by subclasses.
There is no error in compiling, if the method of virtual modifier is rewritten, override must be added in front of it (which tells the compiler that you want to rewrite the virtual method), and there must be an implementation, otherwise the compilation will be wrong:
(3) If a class member is modified by abstract, abstract must be added before the class, because only abstract classes can have abstract methods.

(4) Instances of abstract classes cannot be created, they can only be inherited and cannot be instantiated, for example: BaseTest2 base2 = new BaseTest2(); There will be a compilation error: Abstract class or interface cannot create an instance.

(5) In C#, if you want to rewrite a method in a subclass, you must add virtual before the parent method and override before the subclass method, so as to avoid programmers accidentally rewriting the parent method in the subclass.

(6) The abstract method must be overwritten, and the virtual method must have an implementation (even if it is a method defined in the abstract class).
Interpretation 3
Similarities:
1. They can all be inherited
2. None of them can be instantiated
3. It can contain method declarations
4. Derived classes must implement unrealized methods
Distinguish:
1. Abstract base classes can define fields, attributes, and method implementations. Interfaces can only define attributes, indexers, events, and method declarations, and cannot contain fields.
2. An abstract class is an incomplete class that needs to be further refined, while an interface is a behavioral norm. Microsoft's custom interfaces always come with an able field to prove that they are expressions of the "I can do it..." ”
3. Interfaces can be implemented multiple times, and abstract classes can only be inherited by a single person
4. Abstract classes are more defined between a series of closely related classes, while most of the interfaces are loosely related but all implement a certain function
5. Abstract classes are concepts abstracted from a series of related objects, so they reflect the internal commonality of things; An interface is a functional convention defined to satisfy external calls, so it reflects the external characteristics of things
6. The interface basically does not have any specific characteristics of inheritance, it only promises a method that can be called
7. The interface can be used to support callbacks, but inheritance does not have this feature
8. The specific methods implemented by abstract classes are virtual by default, but the interface methods in the class that implement the interface are non-virtual by default, of course, you can also declare them virtual
9. If the abstract class implements the interface, the method in the interface can be mapped to the abstract class as an abstract method without having to implement it, but the method in the interface can be implemented in the subclass of the abstract class
Rules of use:
1. Abstract classes are mainly used for closely related objects, while interfaces are best used to provide general functionality for irrelevant classes
2. If you want to design a large functional unit, use abstract classes; If you want to design small, concise functional blocks, use interfaces.
3. If multiple versions of the component are expected to be created, create an abstract class. Once an interface is created, it cannot be changed. If a new version of the interface is required, a completely new interface must be created.
4. If the created function will be used between a wide range of heterogeneous objects, use the interface; If you want to provide common implemented functionality across all implementations of a component, use abstract classes.
5. Analyze the object, refine the internal commonality to form an abstract class, which is used to express the essence of the object, that is, "what". Interfaces are prioritized when external calls or functions need to be expanded
6. A good interface definition should be specific and functional, not multi-functional, otherwise it will cause interface pollution. If a class only implements one function of the interface, but has to implement other methods in the interface, it is called interface pollution
7. Try to avoid using inheritance to achieve the formation function, but use black box multiplexing, that is, object combination. Because of the increase in the number of inheritance levels, the most direct consequence is that when you call a class in this taxon, you have to load them all into the stack! The consequences can be imagined. (Combined with stack principle understanding). At the same time, interested friends can notice that Microsoft often uses the method of object combination when building a class. For example, in asp.net, the Page class has properties such as Server Request, but in fact they are all objects of a certain class. Using this object of the Page class to call the methods and properties of other classes is a very basic design principle
For example:
Window forms can be designed with abstract classes, and public operations and properties can be placed in an abstract class, so that the form and dialog box can inherit from this abstract class, and then expand and improve according to their own needs.

The print operation can be provided as an interface to each form that needs this function, because the content of the form is different, and they have to implement their own printing function according to their own requirements. When printing, it is only called through the interface, regardless of which form is being printed.

Commonality, Individuality and Choice:
Some books write that C# recommends using interfaces instead of abstract base classes, and emphasize the many benefits of using interfaces, which I dare not disagree with, from the above list, there are still many differences between the two, and the existence of this difference must determine the difference in applicable scenarios, for example, in the abstract base class can provide default implementations for some methods, so as to avoid repeated implementation of them in subclasses and improve the reusability of code. This is the advantage of abstract classes; The interface can only contain abstract methods. As for when to use abstract base classes and when to use interfaces, it depends on how users view the connections between inherited classes, whether they are personality differences or common connections between them. Let me illustrate with a life example.

If you are given three objects namely people, fish, and frogs, and you are asked to design a base category for them to summarize the connection between them, then the first thing you will feel is that there are great differences between them, and it is difficult to abstract the commonalities. This is where you should consider using interfaces instead of abstract base classes for three reasons:
1. Individuality is greater than commonality.
2. Personalities with large differences have some of the same behaviors.
3. There are great differences in the realization methods of the same behavior.
At this time, you are given three more objects, namely crucian carp, carp, and goldfish, and still let you design base classes to summarize the connection between them, then the first thing you realize is that they all belong to fish, and the second is that the way they swim may be slightly different, so you should use abstract base classes instead of interfaces, compared to the above example, there are three reasons:
1. Commonality is greater than individuality
2. Individuals with the same commonality must have the same attributes and behaviors
3. There are certain differences in the implementation methods of the same behavior
Among the several reasons for using interfaces or abstract base classes, the third reason is actually the same, which describes the concept of polymorphism in object-oriented, that is, it is implemented by overriding the parent class and calling the corresponding method at runtime according to the object reference passed. The second reason begins to diverge, with interfaces emphasizing the same behavior between inherited objects, while abstract classes also emphasize the same properties between inherited objects. What really distinguishes interfaces from abstract base classes is the following reasons:

Interfaces are used when functional commonality is sought between objects with large differences.
Abstract base classes are used when functional differences are sought between objects with more commonality.
By comparing the same and different, we can only say that interfaces and abstract classes have their own strengths, but there are no advantages. In actual programming practice, we need to measure our talents according to the specific situation, but the following experience and accumulation may give you some inspiration, in addition to some of my accumulation, many of them come from the classics, I believe they can stand the test. So in the rules and occasions, we learn these classics, the most important thing is to apply what we have learned, of course, I will win everyone's laughter with the words of a family, please continue.

Rules and occasions:
1. Remember that one of the most important principles of object-oriented thinking is: interface-oriented programming.
2. With the help of interfaces and abstract classes, many ideas in the 23 design patterns have been cleverly implemented, and I think their essence is simply that they are oriented to abstract programming.
3. Abstract classes should be mainly used for closely related objects, while interfaces are best used to provide general functionality for irrelevant classes.
4. The interface focuses on the CAN-DO relationship type, while the abstract class focuses on the IS-A relationship.
5. The behavior of multi-defined objects in the interface; abstract classes multi-define the properties of objects;
6. Interface definitions can use public, protected, internal and private modifiers, but almost all interfaces are defined as public, so there is no need to say more.
7. "The interface remains unchanged" is an important factor that should be considered. Therefore, when adding extensions from interfaces, new interfaces should be added, not existing interfaces.
8. Try to design the interface into a functional block with a single function, taking .NET Framework as an example, IDisposable, IDisposable, IComparable, IEquatable, IEnumerable, etc. all contain only one common method.
9. The capital letter "I" in front of the interface name is a convention, just like the field name starts with a underscore, please adhere to these principles.
10. In the interface, all methods default to public.
11. If version problems are expected, you can create an "abstract class". For example, if you create a dog, a chicken, and a duck, you should consider abstracting animals to deal with things that may arise in the future. Adding new members to the interface forces all derived classes to be modified and recompiled, so versioning problems are best implemented with abstract classes.
12. Non-abstract classes derived from abstract classes must include all inherited abstract methods and actual implementations of abstract accessors.
13. The new keyword cannot be used for abstract classes, nor can they be sealed, because abstract classes cannot be instantiated.
14. Static or virtual modifiers cannot be used in abstract method declarations.





Previous:C# Enum Simple Permission Design uses the FlagsAttribute property
Next:Huang Yong's Yiyun classroom has a zero-based understanding of the WeChat mini program
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com