Change values in Class Attribute at runtime

非 Y 不嫁゛ 提交于 2019-12-10 13:19:24

问题


If I have a class like this

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

Is there a way I can change the values of the attribute of an instance of the class at runtime? eg in pseudo code

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

(I have an instance of the class I want to change the attributes on, cast as a class it extends)


回答1:


There is no implicit connection between attributes and objects instances. Only between the class and the attribute. The best bet would be to look for the attribute in the constructor and "cache" the values in properties on the object. Of course that doesn't make sense if you are only looking at the Test class, but it does make sense if the constructor of the SuperClass looks for the custom attributes on the type retrieved with "this.GetType()".




回答2:


You can change Attribute values at runtime at Class level (not object instance level):

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


来源:https://stackoverflow.com/questions/15374934/change-values-in-class-attribute-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!