如何使用reflection设置属性值
我有一个用属性装饰的类… [DataEntity("MESSAGE_STAGING", EnableCaching = true, CacheTimeout = 43200)]
对于某些要求,我想在运行时将此值MESSAGE_STAGING
更改为Test_Message_Staging
。
实现这一目标的最佳方法是什么?
我可以使用reflection,还是有其他方法可以做到这一点。
请提供代码示例。
谢谢SNA
我不相信用reflection设置属性是可能的 – 即使它是,我鼓励你不要这样做。
属性应该用于在编译时已知的元数据。 如果你想要一个更动态的元数据forms,从文件中加载它或者使用app.config代替……或者至少有一些特殊的“占位符”值(比如连接字符串中的| DataDirectory |)可以在执行时解析时间。
使用reflection在运行时更改属性属性值是不可能的,因为属性是在程序集中序列化的元数据,更改它们意味着更改程序集。
如果我理解正确,有一种可能的方法可以在运行时更改实例的属性值。结帐示例代码
上述就是C#学习教程:如何使用reflection设置属性值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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 }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1041894.html