Changing Attribute Parameters Dynamically
It is not immediately apparent whether you can modify attribute parameters during runtime. For instance, consider the following class supplied by a third party vendor:
public class UserInfo { [Category("change me!")] public int Age { get; set; } [Category("change me!")] public string Name { get; set; } }
You realize the provided category descriptions are inaccurate and wish to modify them without altering the original code. How can this be achieved?
Modifying Attribute Instances Dynamically
It turns out that you can indeed modify attribute instance values at runtime. Attribute instances are ordinary objects, allowing for unrestricted manipulation. The following steps demonstrate how:
Retrieve the attribute instances from the type:
ASCII[] attrs1=(ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
Modify the public variable of the retrieved attribute:
attrs1[0].MyData="A New String";
Show the modified value:
MessageBox.Show(attrs1[0].MyData);
Create a new attribute instance to verify the original value is unchanged:
ASCII[] attrs3=(ASCII[]) typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); MessageBox.Show(attrs3[0].MyData);
This demonstrates the ability to dynamically adjust attribute parameters at runtime.
The above is the detailed content of Can Attribute Parameters Be Dynamically Changed at Runtime?. For more information, please follow other related articles on the PHP Chinese website!