我正在尝试按高度排序对象列表。这个列表包含TextChunk
和Rectangle
类型,所以它将是非常方便的,只是做一个接口,他们都符合,其中包含他们的最大高度,然后排序。问题是,我不知道如何使我导入的类符合接口。c#新手,所以请原谅我的基本问题。
不能为已经存在的类添加接口。
你能做的是写一个带有隐式转换的包装器类,使你的工作更容易。
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