c# - C# 中的流畅接口(interface)和多重继承

标签 c# inheritance multiple-inheritance fluent-interface

这个问题类似于 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 继承两个类,而是引用这些类的对象。它将不得不重新定义每个类的方法。您可以向 CircleBox 添加隐式转换,以允许在需要引用这些对象的上下文中使用它。

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/

相关文章:

c# - 查找正则表达式以获取具有文件扩展名的子字符串

c# - 我可以在 linq 中实现属性并且不调用方法两次吗?

c# - 将 POCO 对象类和 DBContext 从 Entity Framework 6 模型中分离出来

c# - 如何获取字符串中的向量位置并将其存储为整数?

Java:使用 super 调用时隐藏父类(super class)字段的值是多少?

python - 为什么Python的C3 MRO依赖于一个公共(public)基类?

c++ - 为什么这个来自模板类型 "stack"类的 isEmpty() 没有继承到 C++ 中模板类型的派生类 "specialStack"?

c# - 如何在 C# 中使用类的类型作为继承的集合属性的类型参数

java - Java 中带有抽象类的菱形继承(钻石问题)

c++ - 在 OMNeT++ 中使用多重继承时是否存在任何已知问题?