由于多重继承不好(它使源代码更复杂),C# 不直接提供这样的模式。但有时拥有这种能力会很有帮助。
例如,我可以使用接口(interface)和类似的三个类来实现缺少的多重继承模式:
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(); }
}
每次我向其中一个接口(interface)添加方法时,我也需要更改类 FirstAndSecond。
有没有办法像在 C++ 中那样将多个现有类注入(inject)到一个新类中?
也许有使用某种代码生成的解决方案?
或者它可能看起来像这样(假想的 c# 语法):
public class FirstAndSecond: IFirst from First, ISecond from Second
{ }
这样当我修改其中一个接口(interface)时就不需要更新类 FirstAndSecond。
编辑
也许考虑一个实际的例子会更好:
您有一个现有的类(例如基于 ITextTcpClient 的基于文本的 TCP 客户端),您已经在项目中的不同位置使用了该类。现在您觉得有必要为您的类创建一个组件,以便 Windows 窗体开发人员可以轻松访问。
据我所知,您目前有两种方法可以做到这一点:
编写一个从组件继承的新类,并使用类本身的实例实现 TextTcpClient 类的接口(interface),如 FirstAndSecond 所示。
编写一个继承自 TextTcpClient 并以某种方式实现 IComponent 的新类(尚未真正尝试过)。
在这两种情况下,您都需要按方法而不是按类进行工作。既然您知道我们将需要 TextTcpClient 和 Component 的所有方法,那么将这两个组合到一个类中将是最简单的解决方案。
为了避免冲突,这可以通过代码生成来完成,在代码生成之后可以更改结果,但是手动输入这个纯粹是一件很痛苦的事。
最佳答案
考虑只使用 composition 而不是试图模拟多重继承。您可以使用接口(interface)来定义组成组合的类,例如:ISteerable
表示 SteeringWheel
类型的属性,IBrakable
表示类型的属性BrakePedal
等
完成后,您可以使用 Extension Methods添加到 C# 3.0 的功能可进一步简化对这些隐含属性的调用方法,例如:
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(); }
}
public static class SteeringExtensions
{
public static void SteerLeft(this ISteerable vehicle)
{
vehicle.wheel.SteerLeft();
}
}
public static class BrakeExtensions
{
public static void Stop(this IBrakable vehicle)
{
vehicle.brake.ApplyUntilStop();
}
}
public class Main
{
Vehicle myCar = new Vehicle();
public void main()
{
myCar.SteerLeft();
myCar.Stop();
}
}
关于c# - C#中的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/178333/