2015-05-20 39 views
0

請幫我添加在DisplayAttribute一個屬性格式我試過,但得到consturtor誤差爲空通過TypeBuilder添加DisplayAttribute

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

回答

4

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

謝謝你的工作@Antonio – Shiljo

+0

當然,如果你不介意&如果你有答案你能告訴我如何在其中添加Order屬性嗎? display屬性還有其他附加參數,如訂單,名稱。你給我看的名字 – Shiljo

+0

查看我的更新回答 –