我有一个被属性修饰的类...
[DataEntity("MESSAGE_STAGING", EnableCaching = true, CacheTimeout = 43200)]
由于某种需求,我想在运行时将这个值 MESSAGE_STAGING
更改为 Test_Message_Staging
。
有没有最好的方法来实现这一点?
我可以使用反射吗,或者还有其他方法可以做到这一点。
请提供代码示例。
谢谢 SNA
我不相信可以使用反射来设置属性 - 即使可以,我也鼓励您不要这样做。
属性应该用于在编译时已知的元数据。如果您想要更动态的元数据形式,请从文件中加载或使用app.config... 或者至少有一些特殊的“占位符”值(如连接字符串中的|DataDirectory|),可以在执行时解析。
使用反射在运行时更改属性值是不可能的,因为属性是元数据序列化在程序集中的,更改它们意味着更改程序集。
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
}