c#设置customattribute的属性

时间:2017-06-09 15:40:16

标签: c# .net reflection custom-attributes

我创建了一个名为AttributeConfiguration的自定义类,其中包含以下属性。

public class AttributeConfiguration : Attribute
{
        public string DisplayName { get; set; }
        public string SchemaNameCRM { get; set; }
        public string SchemaNameERP { get; set; }
        public bool Required { get; set; }
        public bool IsChild { get; set; }
}

我还有一些其他类使用我的自定义类AttributeConfiguration来修饰它的属性。

public class Client
{
    public Client()
    {
          //Here I want to set all properties of my custom attribute 
          //AttributeConfiguration that decorates my attribute CODE
    }

    [AttributeConfiguration()]
    public string Code { get; set; }
}

我需要设置自定义类AttributeConfiguration的属性,它在我的客户端实体的构造函数中装饰我的属性代码。

这是我到目前为止所尝试过的。

//PROPERTY OF MY CLASS
 var property = this.GetType().GetProperty("Code");

//MY CUSTOM ATTRIBUTE CONFIGURATOIN
AttributeConfiguration propertyConfigurationBeforeChange = property.GetCustomAttributes(false)
.Where(c => c.GetType() == typeof(AttributeConfiguration)).FirstOrDefault() as AttributeConfiguration;

 //GET SchemaNameERP from my Custom AttributeConfiguration instance
 PropertyInfo propertySchemaNameERP = propertyConfigurationBeforeChange.GetType().GetProperty("SchemaNameERP");
//CHANGING DEFAULT VALUE = Default Value is "ValueNotApplied"
propertySchemaNameERP.SetValue(propertyConfigurationBeforeChange, "NEW VALUE", null);

//SchemaNameERP property of my custom class instance propertyConfigurationBeforeChange has changed to my NEW VALUE 

  ///GETTING VALUE OF MY CUSTOM ATTRIBUTE CONFIGURATOIN FOR THE SECOND TIME AND IT HASN'T CHANGED THE DEFAULT VALUE
  attributeConfiguration propertyConfigurationAfterChange = property.GetCustomAttributes(false)
   .Where(c => c.GetType() == typeof(AttributeConfiguration)).FirstOrDefault() as AttributeConfiguration;

在这个例子中,我试图仅更改属性SchemaNameERO的值,但是我只能更改我创建的实例(propertyConfigurationBeforeChange变量)的atrribute的值,但不能更改实际实例中的& #34;在#34;物业代码。

我被困了一整天。

我感谢任何帮助。

0 个答案:

没有答案