Created
June 1, 2017 16:21
-
-
Save audinue/4522260772413e05bc43472f42da1b3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var assembly = AssemblyDefinition.ReadAssembly("Cecil.exe"); | |
var module = assembly.MainModule; | |
var type = module.GetType("Cecil.Program"); | |
foreach (var field in type.Fields.Where(f => f.IsPublic && f.CustomAttributes.Any(a => a.AttributeType.Name == "ToPropertyAttribute")).ToArray()) | |
{ | |
var newField = new FieldDefinition("_" + field.Name, FieldAttributes.Private, field.FieldType); | |
newField.InitialValue = field.InitialValue; | |
var newProperty = new PropertyDefinition(field.Name + "X", PropertyAttributes.None, field.FieldType); | |
newProperty.HasThis = true; | |
newProperty.SetMethod = new MethodDefinition("set_" + field.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, module.Import(typeof(void))); | |
var par = new ParameterDefinition("value", ParameterAttributes.None, field.FieldType); | |
newProperty.SetMethod.SemanticsAttributes |= MethodSemanticsAttributes.Setter; | |
newProperty.SetMethod.Parameters.Add(par); | |
var processor = newProperty.SetMethod.Body.GetILProcessor(); | |
processor.Emit(OpCodes.Ldarg_0); | |
processor.Emit(OpCodes.Ldarg, par); | |
processor.Emit(OpCodes.Stfld, newField); | |
processor.Emit(OpCodes.Ret); | |
type.Fields.Remove(field); | |
type.Fields.Add(newField); | |
type.Methods.Add(newProperty.SetMethod); | |
type.Properties.Add(newProperty); | |
} | |
assembly.Write("Cecil2.exe"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment