SoFunction
Updated on 2025-03-08

Detailed explanation of the specific implementation and function of C# object-oriented features

As we all know, the characteristics of object-oriented programming are: encapsulation, inheritance, and polymorphism. C# is a completely object-oriented language. Since it was launched later than Java, it embodies object-oriented ideas even more perfect than Java. So how do you embody encapsulation, inheritance and polymorphism in C#? The following examples are given and explained.

1. Packaging

The benefits of packaging are as follows:

① Data is not leaked, and can provide certain protection

②Class users do not need to consider specific data operations, which is convenient

③The program is highly structured, clear in hierarchy, easy to maintain

Encapsulation of related fields and methods certainly plays an indispensable and important role in object-oriented programming, but it does not mean that the content in the class or specific instantiated object cannot be accessed. It also provides users with interfaces and only allows them to call. They only do their work, and do not need to consider or consider what the class you write does, let alone what each line of code you write means.

In C#, the encapsulation of variables often needs to be called outside of this class and appear in the form of attributes, unlike in C++, which directly calls with public members or private members plus related methods, which either does not conform to the object-oriented characteristics or is too troublesome.

Declaration of properties in C#:

Copy the codeThe code is as follows:

public class TestClass
    {
        public string Info
        {
            get;
            set;
        }
    }

The declaration of an attribute is similar to a function. First, there is an access level (if it is set to private, it is better to write a variable directly), then the type, followed by the attribute name, followed by a pair of curly braces. The get and set inside are used to control whether the attribute is read-only, write-only, or readable and writeable. Of course, get and set here end directly with a semicolon, which is called automatic attributes. If necessary, you can also customize get and set. The return type that always matches the attribute type needs to be added in the get.

C# encapsulation of methods only requires changing the access level of the method, such as setting it to public, or setting it to private (or not writing), which corresponds to being accessible from the outside and only being accessible from the inside.

2. Inheritance

Everyone knows that the inheritance mechanism can improve the reusability and scalability of code, so as to improve development efficiency and reduce the amount of code. C# and C++ are different. They can inherit from one class or implement multiple interfaces, but they cannot inherit from multiple classes.

Inheritance syntax example:

Copy the codeThe code is as follows:

class Son : Father
{
      //Do Something
}

Inheritance can enable subclasses or derived classes to obtain all inheritable contents of the parent class or base class, such as fields and methods, but there are certain restrictions on the access level, that is, the private level cannot be inherited. In addition to this, it should be noted here that if you need to call members in the base class (parent class), you need to use the base keyword, and if you need to use the members in the current class in the method, but because of the duplicate names (such as parameters and class member variables are duplicate names), you need to use this keyword to determine which member is accessed.

All C# classes are inherited from, so no matter what class it is, there are several fixed and public methods. This is a very good thing about C# reflecting the object-oriented idea!

Let’s talk about the characteristics of static classes:

① Static classes cannot use sealed or abstract modifiers

② Static classes must be inherited directly from, not other

③ Static classes cannot implement any interface

④ Static classes cannot contain any operators

⑤ Static classes cannot contain static members modified with protected or protected internal

⑥ Static class intelligence contains static members

⑦ Static classes can contain static constructors, but cannot contain instance constructors.

⑧ Static classes cannot be instantiated

⑨ Static classes are sealed and cannot be inherited

Since static classes are automatically loaded by the CLR when loading the assembly containing the class, it is a very good choice to use static classes to implement some methods that do not manipulate data and are not associated with specific objects in the code.

The rest to note is to clarify the order of calling the constructor when using inheritance, first initialize the instance field of the class, then call the base class constructor, and finally call your own constructor.

3. Polymorphism

When calling methods implemented in derived classes through references to base classes, different derived classes will produce different call results, which is polymorphism, and polymorphisms in C# are divided into runtime polymorphism and compile-time polymorphism. Compilation-time polymorphism is implemented using function overload, and run-time polymorphism is implemented by overwriting virtual methods.

① Method overloading

Prerequisite: In the same class, the method name is the same and the method signature is different (including the method name and parameter information (modifiers, number, type, and number of generic parameters of formal parameters), but the name of the return value type, formal parameter and type parameter does not belong to part of the method signature)

Method overloading example:

Copy the codeThe code is as follows:

public string Function(int x)
{
 return ();
}
public string Function(DateTime x)
{
 return ("yyyy-MM-dd HH:mm:");
}
public string Function(double x,double y)
{
 return (x+y).ToString();
}

The above example implements a three overload called Function and returns a type string, which is to return an int parameter to a string, return a DateTime parameter to a string format "Year-Month-Day Time: Minutes: Seconds. Milliseconds", and convert the sum of the two double parameter to a string type

②Virtual method

To define a virtual method, you need to use the virtual keyword, as shown below:

Copy the codeThe code is as follows:

class Car
{
 public virtual void Drive()
 {
("Driving...");
 }
}

The reason why Drive is set as a virtual method is to allow the derived subclasses to be rewrite so that all Car derived classes can implement new Drive methods.

Note: The virtual keyword must be before the return type of the return method. The virtual method can have a method body, while the abstract method does not allow a method body.

Note: Static member functions cannot be virtual functions, and constructors cannot be virtual functions.

Example of overwriting method:

Copy the codeThe code is as follows:

class Track : Car
{
 public override void Drive()
 {
("Driving a big truck");
 }
}
class Jeep : Car
{
 public override void Drive()
 {
("Driving a Jeep");
 }
}

③Abstract classes and abstract methods
There are some notes: (1) They cannot be instantiated (2) The abstract method cannot have a method body, the class where it is located must be an abstract class (3) Use the abstract keyword (4) The abstract method has no implementation, followed by the semicolon (5) The derived class of the abstract class must implement all abstract methods (6) When the abstract class inherits a virtual method from the base class, the abstract class can rewrite the virtual method using the abstract method.

I won't give specific examples

4. Summary

All the concept of facial objects is ultimately to simplify code, reduce the amount of code, and build program code that is more in line with the logic of real life, thereby reducing the burden on programmers. We cannot blindly or deliberately use the idea of ​​facial objects and ignore the functions or frameworks implemented by the program. We must reasonably use the idea of ​​facial objects according to actual conditions to reduce the burden and provide convenience to others!