这个问题类似于 this one 强>。区别在于我想要两个基类。
示例:
public class Circle
{
private string _radius { get; set; }
public Circle Radius(string radius)
{
_radius = radius;
return this;
}
}
public class Box
{
private string _width { get; set; }
public Circle Width(string width)
{
_width = width;
return this;
}
}
public class CircleAndBox : Circle, Box // Can't do in c#
{
// should contain methods from both Circle and Box, but return CircleAndBox
}
也许 Circle 和 Box 不是最好的例子。基本上它们代表具有不同属性和方法的类。 CircleAndBox 类恰好与 Circle 和 Box 具有相同的属性和方法。 CircleAndBox 可能具有 Circle 和 Box 中都不存在的其他属性和方法。
期望的结果
我应该能够写:
var circle = new Circle().Radius("5");
var box = new Box().Width("6");
var circleAndBox = new CircleAndBox().Radius("5").Width("6");
如果满足以下条件,那就太棒了:
当我向 Circle
添加方法时或 Box
类,我不应该碰CircleAndBox
类(class)。就像从单个类的常规继承一样,CircleAndBox
应该自动从 Circle
继承所有公共(public)方法和 Box
最佳答案
让 CircleAndBox
继承两个类,而是引用这些类的对象。它将不得不重新定义每个类的方法。您可以向 Circle
和 Box
添加隐式转换,以允许在需要引用这些对象的上下文中使用它。
public class CircleAndBox
{
public Circle Circle { get; private set; }
public Box Box { get; private set; }
public CircleAndBox()
{
Circle = new Circle();
Box = new Box();
}
public CircleAndBox Radius(string radius)
{
Circle.Radius(radius);
return this;
}
public CircleAndBox Width(string width)
{
Box.Width(width);
return this;
}
public static implicit operator Circle(CircleAndBox self)
{
return self == null ? null : self.Circle;
}
public static implicit operator Box(CircleAndBox self)
{
return self == null ? null : self.Box;
}
}
请注意,隐式转换不会保留对象的类型,因此不应使用此技术将 CircleAndBox
传递给采用 Box
的方法并期望另一边的结果是 CircleAndBox
。
CircleAndBox cb = new CircleAndBox();
// Implicit conversion, b contains a Box object.
Box b = cb;
// Compile-time error CS0030.
cb = (CircleAndBox)b;
关于c# - C# 中的流畅接口(interface)和多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18026470/