我是 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/