Tôi cần tham số của thuộc tính thay đổi trong thời gian chạy. Tôi đã đơn giản hóa vấn đề của mình thành ví dụ đơn giản.Thay đổi thông số của thuộc tính tùy chỉnh tại thời gian chạy
Thuộc tính lớp:
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string Name { get; set; }
}
Simple thực thể Mà đã trang trí thuộc tính với các thuộc tính:
public class MyEntity
{
[MyAttribute(Name="OldValue1")]
public string Data1{ get; set; }
[MyAttribute(Name = "OldValue2")]
public string Data2 { get; set; }
}
Tôi tạo ra instace của lớp MyEntity. Tôi có thể thay đổi giá trị của các thuộc tính của đối tượng, nhưng tôi không thể thay đổi giá trị của tên thuộc tính của thuộc tính trên thực thể đối tượng. Có thể không?
Giá trị của tài sản trên thực thể đối tượng tôi có thể thay đổi với phần mã này:
entityProp.SetValue(entity,"NewData",null);
nhưng tôi không thay đổi giá trị như thế nào của thuộc tính Tên tài sản trên đối tượng thực thể
này không hoạt động:
attProp.SetValue(attribute,"NewData",null);
Giá trị Tên propery vẫn còn nguyên bản.
Đây là tất cả mã kiểm tra. Cảm ơn bạn vì hellp.
[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));
}
}
}
CHỈNH SỬA: Tôi xóa bài gốc và thêm mẫu rất đơn giản. Xin lỗi
Lưu ý phụ: tại sao phương pháp thứ hai của bạn lại bắt và sau đó ném ngoại lệ? –