SoFunction
Updated on 2025-05-21

Analysis of the principle of substitution of Lisch in C# inheritance

C# Richter replacement principle

1. Concept

The Richter replacement principle is one of the basic principles of object-oriented design:

  • Core idea:All places where base classes are referenced must be able to use objects of its subclasses transparently.That is, subclass objects can replace base class objects without affecting the correctness of the program.
  • Performance:The parent container can load subclass objects, but the subclass container cannot load parent objects.

2. Grammatical expression

//The parent class container loads the subclass object// Player and Monster are subclasses of GameObjectGameObject player=new Player();
GameObject monster=new Monster();

//Subclass container cannot load parent class object
//Player p=new GameObject();

3. Type checking and conversion

C# ProvidedisandasOperators to handle type checking and conversion.

if(player is Player)
{

  (player as Player).PlayerAtk();

}
  • isUsed to check whether an object belongs to a specific type
  • asIt is used for safe conversion, which is safer than strong conversion.asnull will be returned when the conversion fails.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.