![](/img/trans.png)
[英]MissingMethodException when calling to a class library from third-party application
[英]C# - import class from third-party library and make it a derived class (or something similar)
我是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 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#不允許您從兩個類派生,因此它不能充當圓(不會從圓繼承)。 這意味着它們的基類或您的基類都必須是接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.