如何使用reflection设置属性值

我有一个用属性装饰的类… [DataEntity("MESSAGE_STAGING", EnableCaching = true, CacheTimeout = 43200)]

对于某些要求,我想在运行时将此值MESSAGE_STAGING更改为Test_Message_Staging

实现这一目标的最佳方法是什么?

我可以使用reflection,还是有其他方法可以做到这一点。

请提供代码示例。

谢谢SNA

我不相信用reflection设置属性是可能的 – 即使它是,我鼓励你不要这样做。

属性应该用于在编译时已知的元数据。 如果你想要一个更动态的元数据forms,从文件中加载它或者使用app.config代替……或者至少有一些特殊的“占位符”值(比如连接字符串中的| DataDirectory |)可以在执行时解析时间。

使用reflection在运行时更改属性属性值是不可能的,因为属性是在程序集中序列化的元数据,更改它们意味着更改程序集。

如果我理解正确,有一种可能的方法可以在运行时更改实例的属性值。结帐示例代码

  AttributeCollection ac = TypeDescriptor.GetAttributes(yourObj); foreach (var att in ac) { //DataEntityAttribute -- ur attribute class name DataEntityAttribute da = att as DataEntityAttribute ; Console.WriteLine(da.field1); //initially it shows MESSAGE_STAGING da.field1= "Test_Message_Staging"; } //Check the changed value AttributeCollection acc = TypeDescriptor.GetAttributes(yourObj); foreach (var att in ac) { DataEntityAttribute da = att as DataEntityAttribute ; Console.WriteLine(da.field1); //now it shows Test_Message_Staging }