How to set attributes values using reflection

前端 未结 3 1662
感动是毒
感动是毒 2020-11-29 13:01

I have a class decorated with a attribute ...[DataEntity(\"MESSAGE_STAGING\", EnableCaching = true, CacheTimeout = 43200)]

for some requirement,I want t

相关标签:
3条回答
  • 2020-11-29 13:39

    It's not possible to change attribute property value at run-time with reflection because attributes are meta-data serialized in the assembly and changing them means changing the assembly.

    0 讨论(0)
  • 2020-11-29 13:51

    I don't believe it's possible to set attributes using reflection - and even if it is, I'd encourage you not to do so.

    Attributes should be used for metadata which is known at compile-time. If you want a more dynamic form of metadata, load it from a file or use app.config instead... or at least have some special "placeholder" values (like |DataDirectory| in a connection string) which can be resolved at execution time.

    0 讨论(0)
  • 2020-11-29 13:59

    If i understand you correctly, there is a possible way in reflection to change the attribute value of a instance at runtime.. checkout the sample code

            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
            }
    
    0 讨论(0)
提交回复
热议问题