Ändern Sie den Parameter des benutzerdefinierten Attributs zur Laufzeit
Ich benötige den Parameter des Änderungsattributs zur Laufzeit. Ich habe mein Problem zu einem einfachen Beispiel vereinfacht.
Attributklasse:
<code> [AttributeUsage(AttributeTargets.Property)] public class MyAttribute : Attribute { public string Name { get; set; } } </code>
Einfache Entität, die Eigenschaften mit Attributen dekoriert hat:
<code> public class MyEntity { [MyAttribute(Name="OldValue1")] public string Data1{ get; set; } [MyAttribute(Name = "OldValue2")] public string Data2 { get; set; } } </code>
Ich habe eine Instanz der Klasse MyEntity erstellt. Ich kann den Wert der Objekteigenschaften ändern, aber den Wert der Attributeigenschaft Name für die Objektentität nicht. Ist es möglich?
Wert der Eigenschaft einer Objektentität, die ich mit diesem Teil des Codes ändern kann:
<code> entityProp.SetValue(entity,"NewData",null); </code>
Ich verändere jedoch nicht den Wert der Eigenschaft Name des Attributs für die Objektentität
Das funktioniert nicht:
<code>attProp.SetValue(attribute,"NewData",null); </code>
Wert der Eigenschaft Name ist noch original.
Hier ist der gesamte Testcode. Danke für die Hölle.
<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>
BEARBEITET: Ich lösche den ursprünglichen Beitrag und füge eine sehr einfache, übersichtliche Probe hinzu. Es tut uns leid