How to sort classes/fields/methods/properties in a .NET assembly?

血红的双手。 提交于 2019-12-25 07:35:51

问题


I have an assembly of a program for which I don't have access to the source code and want to sort its classes alphabetically by their fully qualified name inside of the assembly, instead of using the order specified by the compiler used to generate it.

I've tried using Mono.Cecil for that, but it seems I can't change the order of classes within ModuleDefinition.Types property because it's a get-only IEnumerable.

So how do I change the order of the items of an assembly module? Or is it impossible to change it?


回答1:


it seems I can't change the order of classes within ModuleDefinition.Types property because it's a get-only IEnumerable.

Not quite, it's a get-only Collection<T>.

This means you can change the order of types in it by getting the list of types from the collection, sorting them, clearing Types and finally readding them back. In code:

var assembly = AssemblyDefinition.ReadAssembly(inputPath);

var module = assembly.MainModule;

var sorted = module.Types.OrderBy(t => t.FullName).ToList();

module.Types.Clear();

foreach (var type in sorted)
{
    module.Types.Add(type);
}

assembly.Write(outputPath);


来源:https://stackoverflow.com/questions/37901721/how-to-sort-classes-fields-methods-properties-in-a-net-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!