C# - 从第三方库导入类并使其成为派生类(或类似的类)

标签 c# class inheritance derived

我是 C# 初学者。我想从第三方库导入一个类并使其成为派生类(或类似的类)。在下面的示例中,如何创建一个同时具有 CircleSpecificMethods() 和 CommonShapeMethods() 的类?

谢谢!

第三方库:

namespace ThirdPartyLib
{
    public class Circle
    {
        public CircleSpecificMethods()
        {
            ...
        }
    }

    public class Triangle
    {
        public TriangleSpecificMethods()
        {
            ...
        }
    }
}

我的程序:

using ThirdPartyLib;
namespace MyProgram
{
    public class Shape
    {
        public CommonShapeMethods()
        {
            ...
        }
    }

    public class Rectangle : Shape
    {
        public RectangleSpecificMethods()
        {
            ...
        }
    }

    public static class Program
    {
        public static void Main()
        {
            var rectangle = new Rectangle();
            var circle = new Circle();

            rectangle.CommonShapeMethods();
            rectangle.RectangleSpecificMethods();

            circle.CommonShapeMethods(); // How can I make circle to have CommonShapeMethods as well?
            circle.CircleSpecificMethods();
        }
    }
}

最佳答案

您要求的是Adapter Pattern .

Adapter 是一个辅助类,可让您将一个类适配为另一个类。在你的例子中,这将是

// adapter fulfills your requirement, it is a shape
public class CircleToShapeAdapter : Shape 
{
     private Circle _circle { get; set; }

     // but it takes their object as a source
     public CircleToShapeAdapter( Circle circle )
     {
         this._circle = circle;
     }

     // for any method that is required by your Shape specification
     // you just find a way to implement the method using their API
     public void ShapeMethod()
     {
         circle.DoSomething();
     }
}

然后你就可以使用它们的圆圈来创建你的形状

Shape shape = new CircleToShapeAdapter( circle );

请注意,适配器仍然可以公开特定于圆的方法,但它不会充当圆(不会继承它),因为 C# 不允许您从两个类派生。这意味着他们的基类或您的基类必须是接口(interface)。

关于C# - 从第三方库导入类并使其成为派生类(或类似的类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105345/

相关文章:

c# - 如何在 C# 中加载程序图标

c# 将ftp服务器上的图片直接加载到图片框中,无需下载

C# 获取两个相同字符之间的值

c# - 除了默认构造函数给出的内容之外,无法返回任何内容

C# 检查一个类是否是 X,或者是从 X 继承的

c++ - protected 构造函数与纯虚拟析构函数

c++ - 从派生类中删除虚函数

c# - 访问 ASP.NET Core 2.2 类库中的 HttpContext

c++ - 错误 C2440 : 'initializing' : cannot convert from 'classname *' to 'classname'

java - 如何解决 ClassNotFoundException?