Cambiar el parámetro del atributo personalizado en tiempo de ejecución
Necesito cambiar el parámetro del atributo durante el tiempo de ejecución. Simplifiqué mi problema al ejemplo simple.
Clase de atributo:
<code> [AttributeUsage(AttributeTargets.Property)] public class MyAttribute : Attribute { public string Name { get; set; } } </code>
Entidad simple que ha decorado propiedades con atributos:
<code> public class MyEntity { [MyAttribute(Name="OldValue1")] public string Data1{ get; set; } [MyAttribute(Name = "OldValue2")] public string Data2 { get; set; } } </code>
He creado la instancia de la clase MyEntity. Puedo cambiar el valor de las propiedades del objeto, pero no puedo cambiar el valor de la propiedad del atributo Nombre en la entidad del objeto. ¿Es posible?
El valor de la propiedad en la entidad de objeto que puedo cambiar con esta parte del código:
<code> entityProp.SetValue(entity,"NewData",null); </code>
pero no sé cómo cambiar el valor de la propiedad del atributo Nombre en la entidad objeto
Esto no funciona:
<code>attProp.SetValue(attribute,"NewData",null); </code>
Valor de la propiedad El nombre sigue siendo original.
Aquí está todo el código de prueba. Gracias por hellp.
<code> [TestMethod] public void Test() { var entity = new MyEntity { Data1 = "OldData", Data2 = "OldData" }; PropertyInfo[] entityProps = entity.GetType().GetProperties(); foreach (var entityProp in entityProps) { var attribute = Attribute.GetCustomAttribute(entityProp, typeof (MyAttribute)) as MyAttribute; if (attribute != null) { //get attribute’s property NAME PropertyInfo attProp= attribute.GetType().GetProperty("Name"); //get entity property value var propertyValue = entityProp.GetValue(entity, null); //get attribute’s property NAME value var atributeNameValue = attProp.GetValue(entity, null); TestContext.WriteLine(string.Format("property name:{0} property value: {1} : atribute name value: {2}\n", entityProp.Name, propertyValue, atributeNameValue)); //change values entityProp.SetValue(entity,"NewData",null); //how can I change value of property Name on object entity ? attProp.SetValue(attribute,"NewData",null); } } TestContext.WriteLine(string.Format("After change\n")); foreach (var entityProp in entityProps) { var attribute = Attribute.GetCustomAttribute(entityProp, typeof(MyAttribute)) as MyAttribute; if (attribute != null) { PropertyInfo attProp = attribute.GetType().GetProperty("Name"); var propertyValue = entityProp.GetValue(entity, null); var atributeNameValue = attProp.GetValue(entity, null); TestContext.WriteLine(string.Format("property name:{0} property value: {1} : atribute name value: {2}\n", entityProp.Name, propertyValue, atributeNameValue)); } } } </code>
EDITADO: elimino la publicación original y agregué una muestra clara muy simple. Lo siento