通过TypeBuilder添加DisplayAttribute

本文关键字:DisplayAttribute 添加 TypeBuilder 通过 | 更新日期: 2023-09-27 17:50:00

请帮助我添加DisplayAttribute属性,我尝试过,但得到构造器错误为null

            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; }
}

通过TypeBuilder添加DisplayAttribute

使用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);
相关文章:
  • 没有找到相关文章