Hi Stanislas,
That's because you're not updating the HasThis part of the signature
of the methods (the MethodDefinition constructor does it for you, but
you're modifying the attributes after hand) and of the property.
Here's a fixed version of your method that works:
public static PropertyDefinition EmitCreatePropertyForField(this
FieldDefinition field)
{
PropertyDefinition prop = new PropertyDefinition("~NS~P~" + field.Name,
PropertyAttributes.None,
field.FieldType);
prop.HasThis = !field.IsStatic;
ParameterDefinition valueArg;
var attributes = MethodAttributes.Private |
MethodAttributes.SpecialName | MethodAttributes.HideBySig;
if (field.IsStatic) attributes |= MethodAttributes.Static;
var getMethod = new MethodDefinition("get_" + prop.Name, attributes,
field.FieldType);
getMethod.SemanticsAttributes = MethodSemanticsAttributes.Getter;
var setMethod = new MethodDefinition("set_" + prop.Name, attributes,
voidType);
setMethod.SemanticsAttributes = MethodSemanticsAttributes.Setter;
setMethod.Parameters.Add(valueArg=new
ParameterDefinition(field.FieldType));
var getter = getMethod.Body.GetILProcessor();
var setter = setMethod.Body.GetILProcessor();
if(field.IsStatic)
{
getter.Emit(OpCodes.Ldsfld, field));
getter.Emit(OpCodes.Ret));
setter.Emit(OpCodes.Ldarg_0));
setter.Emit(OpCodes.Stsfld, field));
setter.Emit(OpCodes.Ret));
}
else
{
getter.Emit(OpCodes.Ldarg_0));
getter.Emit(OpCodes.Ldfld, field));
getter.Emit(OpCodes.Ret));
setter.Emit(OpCodes.Ldarg_0));
setter.Emit(OpCodes.Ldarg, valueArg));
setter.Emit(OpCodes.Stfld, field));
setter.Emit(OpCodes.Ret));
}
field.DeclaringType.Methods.Add(getMethod);
field.DeclaringType.Methods.Add(setMethod);
prop.GetMethod = getMethod;
prop.SetMethod = setMethod;
field.DeclaringType.Properties.Add(prop);
return prop;
}
On Tue, Nov 30, 2010 at 12:00 PM, Stanislav <[email protected]> wrote:
> Hello! I have a question to you. I dont know how I can make it
> correctly. I have source file (http://nsurgeon.codeplex.com/
> SourceControl/changeset/view/1647#45740). This code should create
> property getter and setter by existing field. But if field is static,
> this code works wrong. Properties, created by this program is static.
> I Check it by reflector. BUT it reflector I can see string "... static
> instance void get_..." Why "instance"? I cant write code like this:
> ldarg ...
> call get_Property
> because get_Property needs object's instance in the stack. Why? Static
> flag of an MethodAttribute is setted.
>
> --
> --
> mono-cecil
--
--
mono-cecil