首页 > 解决方案 > 如何为导入的类实现接口

问题描述

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

标签: c#itext

解决方案


您不能将接口添加到已经存在的类。

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

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

推荐阅读