我需要在运行时更改属性的参数。我将问题简化为简单示例。
属性类:
[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 类的实例。我可以更改对象属性的值,但不能更改对象实体上属性的属性 Name 的值。可能吗?
我可以用这部分代码更改对象实体的属性值:
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));
}
}
}
已编辑:我删除了原始帖子并添加了非常简单清晰的示例。抱歉
最佳答案
您不能在运行时更改属性。它们被嵌入到程序集的元数据中。您的方法正在改变特定实例的内部状态;但是当您再次加载该属性时,您会得到一个不同的实例。
关于c# - 在运行时更改自定义属性的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10046601/