c# - 如何为导入的类实现接口
问题描述
我正在尝试按高度排序对象列表。该列表同时包含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
推荐阅读
- javascript - PostgreSQL docker-compose down 后使用的端口不能再次使用
- nosql - 究竟foundationdb如何击败CAP定理?
- python - pandas - 使用 nans 计算矢量化公式
- python - Pygame 组合精灵
- git - 在 git 中添加不在 GitHub 或 anyHub 上的远程
- javascript - 如何在 Angular 中使用 json2html 和 jquery?
- jsf - 通过 BootsFaces 数据表获取传递给 Java 函数的空值
- google-chrome-devtools - 在 Chrome 开发工具中禁用断点的快捷方式是什么?
- assembly - 大会 - 部门给出奇怪的结果
- python - Groupby 和 cumcount 仅适用于有效行