在运行时我需要change属性的参数.我把我的问题简化为简单的例子.
属性类:
[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);
这不行:
06003
名称的价值仍然是原始的.
这是所有测试代码.谢谢你的地狱
[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,null); //how can I change value of property Name on object entity ? attProp.SetValue(attribute,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,atributeNameValue)); } } }