Runtime Attribute Customization
In development, situations arise where attributes need to be modified during runtime, despite limitations imposed by third-party vendors. Considering a class with attributes like:
public class UserInfo { [Category("change me!")] public int Age { get; set; } [Category("change me!")] public string Name { get; set; } }
Modifying Instances at Runtime
Contrary to perceptions, attribute instances can be modified at runtime. By obtaining the attribute instances, we can make value modifications like:
ASCII[] attrs1 = (ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); attrs1[0].MyData = "A New String"; MessageBox.Show(attrs1[0].MyData);
Preserving Unchanged Attribute Values
It's essential to note that subsequent invocations to retrieve attribute instances will not be affected by the runtime modification:
ASCII[] attrs3 = (ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); MessageBox.Show(attrs3[0].MyData); // Original value
The above is the detailed content of Can You Modify .NET Runtime Attributes Dynamically?. For more information, please follow other related articles on the PHP Chinese website!