gpt4 book ai didi

c# - 通过 TypeBuilder 添加 DisplayAttribute

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:34 25 4
gpt4 key购买 nike

请帮我在 DisplayAttribute 中添加我尝试过的属性,但将 consturtor 错误设置为 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; }
}

最佳答案

使用 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);

关于c# - 通过 TypeBuilder 添加 DisplayAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30342407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com