C#-从第三方库导入类并使其成为派生类(或类似的类)
我是C#的初学者。我想从第三方库导入一个类,并使其成为派生类(或类似的类)。在下面的示例中,如何创建同时具有CircleSpecificMethods()和CommonShapeMethods()的类 谢谢 第三方图书馆:C#-从第三方库导入类并使其成为派生类(或类似的类),c#,class,inheritance,derived,C#,Class,Inheritance,Derived,我是C#的初学者。我想从第三方库导入一个类,并使其成为派生类(或类似的类)。在下面的示例中,如何创建同时具有CircleSpecificMethods()和CommonShapeMethods()的类 谢谢 第三方图书馆: namespace ThirdPartyLib { public class Circle { public CircleSpecificMethods() { ... } }
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();
}
}
}
如果您无法将第三方更改为从
Shape
继承,则您无法执行此操作。您也不能从两个不同的类继承(请参见)。如果您必须执行一些与之相近的操作,请尝试将
Shape
更改为,并创建一个新类,该类将继承Circle
,还将实现您的接口
适配器是一个辅助类,它允许您将一个类适配到另一个类中。在你的例子中,那将是
// 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#不允许从两个类派生。这意味着它们的基类或您的基类必须是接口