【问题标题】:How to implement an interface for an imported class如何为导入的类实现接口
【发布时间】:2021-10-27 20:47:11
【问题描述】:

我正在尝试按高度排序对象列表。该列表同时包含TextChunkRectangle 类型,因此只需制作一个它们都符合的接口,其中包含它们的最大高度然后按此排序,这将非常方便。问题是,我不知道如何使我导入的类符合接口。 C# 新手,请原谅这个基本问题。

【问题讨论】:

  • 简而言之,你不能让你无法控制的类实现你所做的接口。您必须创建另一个您可以控制实现接口的类,并包装导入的类。
  • 正如@HereticMonkey 所写 - 使用adapter 模式。

标签: c# itext


【解决方案1】:

您不能向已存在的类添加接口。

您可以做的是编写一个带有隐式转换的包装类,让您的生活更轻松。

class ShapeWithHeight
{
    private ShapeWithHeight(object shape, int height)
    {
        this.Shape = shape;
        this.Height = height;
    }
    public int Height { get; }
    public object Shape { get; }

    static public implicit operator ShapeWithHeight(TextChunk chunk) => new ShapeWithHeight(chunk, chunk.Height);
    static public implicit operator ShapeWithHeight(Rectangle rectangle) => new ShapeWithHeight(rectangle, rectangle.Height);
}

现在你可以这样做了:

var list = new List<ShapeWithHeight>
{
    new TextChunk { Height = 110 },
    new TextChunk { Height = 120 },
    new TextChunk { Height = 190 },
    new Rectangle { Height = 160 },
    new Rectangle { Height = 130 },
    new Rectangle { Height = 140 }
};

var sortedList = list.OrderBy(x => x.Height).ToList();
foreach (var o in sortedList)
{
    Console.WriteLine("Height: {0} Type: {1}", o.Height, o.Shape.GetType().Name);
}

输出:

Height: 110 Type: TextChunk
Height: 120 Type: TextChunk
Height: 130 Type: Rectangle
Height: 140 Type: Rectangle
Height: 160 Type: Rectangle
Height: 190 Type: TextChunk

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 2015-01-27
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多