简体   繁体   中英

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

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM