Multiple inheritance simulation in C#
Use the interface to simulate more inheritance
C# does not support more inheritance, but can be used to simulate it. The following is an example:
However, the disadvantage of this simulation method is that any interface changes need to be modified
<code class="language-csharp">public interface IFirst { void FirstMethod(); } public interface ISecond { void SecondMethod(); } public class First : IFirst { public void FirstMethod() { Console.WriteLine("First"); } } public class Second : ISecond { public void SecondMethod() { Console.WriteLine("Second"); } } public class FirstAndSecond : IFirst, ISecond { First first = new First(); Second second = new Second(); public void FirstMethod() { first.FirstMethod(); } public void SecondMethod() { second.SecondMethod(); } }</code>
FirstAndSecond
code generation method
Ideally, there should be a way to automatically generate a combination of multiple existing classes. This can be implemented using code generation or fictional C# syntax, as shown below:
Combination alternative
<code class="language-csharp">public class FirstAndSecond : IFirst from First, ISecond from Second { }</code>
Instead of trying to simulate more inheritance, it is better to consider using a combination. The interface can define the combination requirements:
Simplify the expansion method to call
<code class="language-csharp">public interface ISteerable { SteeringWheel wheel { get; set; } } public interface IBrakable { BrakePedal brake { get; set; } } public class Vehicle : ISteerable, IBrakable { public SteeringWheel wheel { get; set; } public BrakePedal brake { get; set; } public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); } }</code>
Compared with the simulation multiple inheritance, this alternative provides a clearer and more flexible method.
The above is the detailed content of How Can Multiple Inheritance Be Simulated in C# and What Are the Alternatives?. For more information, please follow other related articles on the PHP Chinese website!