Changing class attribute values ​​at runtime

If I have a class like this

[Attr("Blah", Data = "Blah")] public class Test : SuperClass{} 

Is there a way to change attribute values ​​of an instance of a class at runtime? e.g. in pseudo code

 SuperClass test = new Test(); test.Attr.Value = "blah1"; test.Attr.Data = "blah2"; 

(I have an instance of the class in which I want to change the attributes, as the class that it extends)

+4
source share
2 answers

There is no implicit connection between attributes and object instances. Only between class and attribute. The best thing would be to look for the attribute in the constructor and "cache" the values ​​in the properties of the object. Of course, this does not make sense if you look only at the Test class, but it makes sense if the SuperClass constructor looks for custom attributes of the type obtained using this.GetType () ".

+2
source

You can change attribute values ​​at run time at the class level (and not at the instance level of the object):

 var attr = TypeDescriptor.GetProperties(typeof(UserContact))["UserName"].Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute; attr.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(attr, username_readonly); 
0
source

Source: https://habr.com/ru/post/1468863/


All Articles