पर कस्टम विशेषता का पैरामीटर बदलें मुझे रनटाइम के दौरान परिवर्तन विशेषता के पैरामीटर की आवश्यकता है। मैंने सरल समस्या के लिए अपनी समस्या को सरल बना दिया।रनटाइम
गुण वर्ग:
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string Name { get; set; }
}
सरल इकाई है जो विशेषताओं के साथ गुण से सजाया गया है:
public class MyEntity
{
[MyAttribute(Name="OldValue1")]
public string Data1{ get; set; }
[MyAttribute(Name = "OldValue2")]
public string Data2 { get; set; }
}
मैं कक्षा MyEntity की instace बनाया। मैं ऑब्जेक्ट की गुणों का मान बदल सकता हूं, लेकिन मैं ऑब्जेक्ट इकाई पर विशेषता गुण की संपत्ति का मूल्य नहीं बदल सकता। क्या यह संभव है? वस्तु इकाई पर संपत्ति का
मूल्य मैं कोड के इस हिस्से के साथ बदल सकते हैं:
entityProp.SetValue(entity,"NewData",null);
लेकिन मैं की विशेषता की संपत्ति नाम कैसे बदल मूल्य वस्तु इकाई
पर नहीं है यह काम नहीं:
प्रॉपर्टी नाम केattProp.SetValue(attribute,"NewData",null);
मूल्य अभी भी मूल है।
यहां सभी परीक्षण कोड हैं। नरक के लिए धन्यवाद।
[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));
}
}
}
संपादित: मैं मूल पोस्ट हटा सकते हैं और बहुत ही सरल स्पष्ट नमूना गयी। क्षमा करें
साइड नोट: आपकी दूसरी विधि क्यों पकड़ रही है और फिर अपवाद फेंक रही है? –