Reputation: 49
I am trying to add new overloaded constructor to an existing type. I tried to do it with emit namespace, however created type doesnt inherit the base class and all other methods.
And after reading some articles, i decided its not possible with .net framework built-in classes.
So I got Mono.Cecil, but couldnt find any decent example how to achieve this.
I have encountered a sample which copies methods, but not props, fields etc.
Upvotes: 3
Views: 2179
Reputation: 34880
This adds an empty constructor
void AddEmptyConstructor(TypeDefinition type, MethodReference baseEmptyConstructor)
{
var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
var method = new MethodDefinition(".ctor", methodAttributes, ModuleDefinition.TypeSystem.Void);
method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseEmptyConstructor));
method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
type.Methods.Add(method);
}
You will need to extend it to pass through the extra parameters.
From here
Upvotes: 8