【问题标题】:How to set attributes values using reflection如何使用反射设置属性值
【发布时间】:2010-01-29 07:18:23
【问题描述】:

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

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

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

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

请提供代码示例。

谢谢 国民经济核算体系

【问题讨论】:

  • 您要解决的根本问题是什么?

标签: c# .net asp.net


【解决方案1】:

我不相信可以使用反射设置属性 - 即使可以,我也建议您不要这样做。

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

【讨论】:

  • 要求我必须以某种方式更改表名。属性不允许从 web.config 中获取值。参数应该是常量。所以我能想到的唯一想法是从反射中获取类的属性(dataEntity)并更改其属性。但是有可能
【解决方案2】:

无法在运行时通过反射更改属性属性值,因为属性是在程序集中序列化的元数据,更改它们意味着更改程序集。

【讨论】:

  • 反射是一种适用于所有类型的通用机制,因为它的基础建立在根 Object 类的 GetType 方法中。它为一个类型返回的信息是不可扩展的,因为它在目标类型编译后不能被修改。
【解决方案3】:

如果我理解正确,有一种可能的反射方式可以在运行时更改实例的属性值。查看示例代码

        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
        }

【讨论】:

  • 这不会持续到实例化的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多