C#如何让导入的类实现接口以完成多类型对象按高度排序
C# 导入第三方类适配自定义高度排序解决方案
你没法修改已导入的TextChunk、Rectangle类源码的前提下,有两种常用实现方案:
方案1:适配器模式(贴合你最初的接口设计思路)
完全匹配你想定义公共接口的规划,扩展性更强:
- 首先定义公共高度接口
public interface IHeightSorter { // 你需要的最大高度属性 double MaxHeight { get; } }
- 分别为两个导入类编写适配包装类,实现上述接口
// TextChunk适配类 public class TextChunkHeightAdapter : IHeightSorter { // 存储原始导入类实例 private readonly TextChunk _original; public TextChunkHeightAdapter(TextChunk original) => _original = original; // 绑定原始类的实际高度属性,替换为你用到的类的真实高度字段/属性名即可 public double MaxHeight => _original.Height; } // Rectangle适配类 public class RectangleHeightAdapter : IHeightSorter { private readonly Rectangle _original; public RectangleHeightAdapter(Rectangle original) => _original = original; public double MaxHeight => _original.Height; }
- 转换列表后排序
// 假设你原始的混合类型列表为 rawList var sortedList = rawList.Select(item => item switch { TextChunk tc => new TextChunkHeightAdapter(tc) as IHeightSorter, Rectangle rc => new RectangleHeightAdapter(rc) as IHeightSorter, _ => throw new ArgumentException("列表包含不支持的对象类型") }) // 按高度升序排序,要降序就用OrderByDescending .OrderBy(item => item.MaxHeight) .ToList();
方案2:自定义比较器(代码更简洁,适合仅需排序的场景)
如果不需要复用公共接口做其他逻辑,可以不用定义接口,直接实现排序比较器:
public class MixedHeightComparer : IComparer<object> { public int Compare(object x, object y) { // 提取不同类型对象的高度,属性名替换为你实际用到的字段 double GetHeight(object obj) => obj switch { TextChunk tc => tc.Height, Rectangle rc => rc.Height, _ => throw new NotSupportedException("不支持的对象类型") }; return GetHeight(x).CompareTo(GetHeight(y)); } }
使用方式:
// 直接对原始列表排序 rawList.Sort(new MixedHeightComparer()); // 或者用LINQ生成新的排序后列表 var sortedList = rawList.OrderBy(item => item, new MixedHeightComparer()).ToList();
注意:以上示例中用到的
Height是默认的高度属性名,请根据你导入的TextChunk、Rectangle类的实际高度字段/属性名替换,数值类型也可根据实际情况调整。
内容的提问来源于stack exchange,提问作者Misguided Chunk
相关产品推荐
相关产品推荐

