问题
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-onlyIEnumerable
.
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