我有多个类型存储在一个列表中,我需要将它们从最具体的类型到最通用的类型进行排序,例如:
Vehicle
Car
Bike
Person
Manager
Programmer
Run Code Online (Sandbox Code Playgroud)
所以它列出了:车辆、汽车、自行车、人员、经理、程序员类型。现在我需要得到有序列表,其中更具体的类型总是在更一般的类型之前:汽车、自行车、车辆、经理、程序员、人。除了 Type.IsAssignableFrom 的一些体操之外,是否有一些简单/优雅的方法来实现这一点?
一种简单的方法是确定每个子类在其层次结构中必须比其父类具有更多类,因此您可以按每种类型层次结构中的类数量进行排序:
var types = new[] {
typeof(Vehicle),
typeof(Car),
typeof(Bike),
typeof(Person),
typeof(Manager),
typeof(Programmer)
};
var ordered = types.OrderByDescending(t => GetHierarchy(t).Count());
Run Code Online (Sandbox Code Playgroud)
使用这个:
private static IEnumerable<Type> GetHierarchy(Type type)
{
while (type != null) {
yield return type;
type = type.BaseType;
}
}
class Vehicle {}
class Car : Vehicle{}
class Bike : Vehicle{}
class Person {}
class Manager : Person{}
class Programmer : Person{}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |