Skip to content

Instantly share code, notes, and snippets.

@audinue
Created June 1, 2017 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/4522260772413e05bc43472f42da1b3c to your computer and use it in GitHub Desktop.
Save audinue/4522260772413e05bc43472f42da1b3c to your computer and use it in GitHub Desktop.
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