通过TypeBuilder添加DisplayAttribute

时间:2015-05-20 06:57:32

标签: c#

请帮我添加DisplayAttribute以获得我试过的但是将consturtor错误视为空

            var fieldName = string.Format("Prop{0}", fieldName);
            FieldBuilder fieldBuilder = segmentBuilder.DefineField(fieldName, typeof(string), FieldAttributes.Private);
            PropertyBuilder propertyBuilder = segmentBuilder.DefineProperty(fieldName, PropertyAttributes.HasDefault, typeof(string), null);
            MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            MethodBuilder getPropertyMethodBuilder = segmentBuilder.DefineMethod("get_" + fieldName, getSetAttr, typeof(string), Type.EmptyTypes);
            ILGenerator ilSetGenerator = getPropertyMethodBuilder.GetILGenerator();
            ilSetGenerator.Emit(OpCodes.Ldarg_0);
            ilSetGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            ilSetGenerator.Emit(OpCodes.Ret);                

            MethodBuilder setPropertyMethodBuilder = segmentBuilder.DefineMethod("set_" + fieldName, getSetAttr, null, new Type[] { typeof(string) });
            ILGenerator ilGetGenerator = setPropertyMethodBuilder.GetILGenerator();
            ilGetGenerator.Emit(OpCodes.Ldarg_0);
            ilGetGenerator.Emit(OpCodes.Ldarg_1);
            ilGetGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            ilGetGenerator.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropertyMethodBuilder);
            propertyBuilder.SetSetMethod(setPropertyMethodBuilder);

实际上我期待像下面这样的属性属性

public class ModelClass
{
    [Display(Name = "Propery Name A")]
    public string ProperyA { get; set; }

    [Display(Name = "Propery Name B")]
    public string ProperyB { get; set; }
}

1 个答案:

答案 0 :(得分:6)

使用CustomAttributeBuilder构建属性,使用SetCustomAttribute方法将其应用于属性:

Type[] constructorParameters = new Type[] { typeof(string)};
ConstructorInfo constructorInfo =   typeof(DisplayNameAttribute).GetConstructor(constructorParameters);
CustomAttributeBuilder displayNameAttributeBuilder = new CustomAttributeBuilder(constructorInfo, new object[] { "Property Name A"});

propertyBuilder .SetCustomAttribute(displayNameAttributeBuilder);

如果要设置其他属性属性,则需要使用CustomAttributeBuilder的另一个构造函数设置属性和值:

Type[] constructorParameters = new Type[0];
ConstructorInfo constructorInfo = typeof(DisplayAttribute).GetConstructor(constructorParameters);

PropertyInfo nameProperty = typeof (DisplayAttribute).GetProperty("Name");
PropertyInfo orderProperty = typeof (DisplayAttribute).GetProperty("Order");

CustomAttributeBuilder displayAttributeBuilder = new CustomAttributeBuilder(constructorInfo, new object[] {  }, new PropertyInfo[]{ nameProperty, orderProperty}, new object[]{"Prop Name", 1} );

custNamePropBldr.SetCustomAttribute(displayAttributeBuilder);