从 Assembly.GetTypes() 获取的类型的排序 [英] Ordering of types fetched from Assembly.GetTypes()
问题描述
我有一个要求,我需要获得以下类型
I have a requirement in which i need to get the types as below
public class Class1
{
}
public class Class2 : Class1
{
}
public class Class3 : Class1
{
}
我可以在目标程序集上调用 Assembly.GetTypes()
并添加从 Class1
派生的所有类.我正在订购这些类型,以便下次使用该订单.该顺序对于内部序列化和反序列化至关重要,因为内部引擎取决于类型的索引而不是类型名称.我无法更改序列化引擎.
I can call the Assembly.GetTypes()
on the target assembly and add all the classes that derive from Class1
. I am ordering the types so that next time, that order will be used.
That order is essential for internal serialization and deserialization as the internal engine depends on the index of the type rather than the type name. I can not alter the serialization engine.
如果将来一个新的类Class4
是从Class1
派生出来的,那么它应该在Class3
之后出现.
If in future a new class Class4
is derived from Class1
, then it should come in the order after Class3
.
我想不出可行的解决方案.
I am not able to think of a solution that is feasible.
是否需要维护一个 xml 文件,其中保留了类型的顺序,如果遇到新类型,是否应该将其添加到 xml 的末尾?
Do, i need to maintain a xml file in which the order of the types are preserved and if i encounter a new type, should that be added at the end of xml?
请帮忙
推荐答案
您可以为订购创建任何自定义规则:例如.模式是 {ClassName}{Index}
You can create any custom rule for ordering: for example. The pattern is {ClassName}{Index}
[Fact]
public void Test()
{
Type baseClass = typeof(Class1);
var result = (from type in Assembly.GetExecutingAssembly().GetTypes()
where type.IsSubclassOf(baseClass)
let index = Regex.Match(type.Name, @"\d+$")
where string.IsNullOrWhiteSpace(index.Value) == false
select new ResultItem { Index = int.Parse(index.Value), Type = type })
.OrderBy(x=>x.Index)
.ToList();
result.ForEach(Console.WriteLine);
}
public class Class1
{
}
public class Class2 : Class1
{
}
public class Class3 : Class1
{
}
private sealed class ResultItem
{
public int Index { get; set; }
public Type Type { get; set; }
public override string ToString()
{
return string.Format("Index: {0}, Type: {1}", Index, Type.Name);
}
}
结果输出:
Index: 2, Type: Class2
Index: 3, Type: Class3
因此,您可以添加任何新课程.
So, you can add any new classes.
这篇关于从 Assembly.GetTypes() 获取的类型的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!