code_junkie

Change Attribute's parameter at runtime

Nov 10th, 2011
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. public class UserInfo
  2. {
  3. [Category("change me!")]
  4. public int Age
  5. {
  6. get;
  7. set;
  8. }
  9. [Category("change me!")]
  10. public string Name
  11. {
  12. get;
  13. set;
  14. }
  15. }
  16.  
  17. ASCII[] attrs1=(ASCII[])
  18. typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
  19.  
  20. attrs1[0].MyData="A New String";
  21. MessageBox.Show(attrs1[0].MyData);
  22.  
  23. ASCII[] attrs3=(ASCII[])
  24. typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
  25. MessageBox.Show(attrs3[0].MyData);
  26.  
  27. Dim prop As PropertyDescriptor = TypeDescriptor.GetProperties(GetType(UserInfo))("Age")
  28. Dim att As CategoryAttribute = DirectCast(prop.Attributes(GetType(CategoryAttribute)), CategoryAttribute)
  29. Dim cat As FieldInfo = att.GetType.GetField("categoryValue", BindingFlags.NonPublic Or BindingFlags.Instance)
  30. cat.SetValue(att, "A better description")
  31.  
  32. using System;
  33. using System.ComponentModel;
  34. using System.Windows.Forms;
  35. class MyCategoryAttribute : CategoryAttribute {
  36. public MyCategoryAttribute(string categoryKey) : base(categoryKey) { }
  37.  
  38. protected override string GetLocalizedString(string value) {
  39. return "Whad'ya know? " + value;
  40. }
  41. }
  42.  
  43. class Person {
  44. [MyCategory("Personal"), DisplayName("Date of Birth")]
  45. public DateTime DateOfBirth { get; set; }
  46. }
  47.  
  48. static class Program {
  49. [STAThread]
  50. static void Main() {
  51. Application.EnableVisualStyles();
  52. Application.Run(new Form { Controls = {
  53. new PropertyGrid { Dock = DockStyle.Fill,
  54. SelectedObject = new Person { DateOfBirth = DateTime.Today}
  55. }}});
  56. }
  57. }
  58.  
  59. public class UserInfo
  60. {
  61. [Category("Must change")]
  62. public string Name { get; set; }
  63. }
  64.  
  65. public class NewUserInfo : UserInfo
  66. {
  67. public NewUserInfo(UserInfo user)
  68. {
  69. // transfer all the properties from user to current object
  70. }
  71.  
  72. [Category("Changed")]
  73. public new string Name {
  74. get {return base.Name; }
  75. set { base.Name = value; }
  76. }
  77.  
  78. public static NewUserInfo GetNewUser(UserInfo user)
  79. {
  80. return NewUserInfo(user);
  81. }
  82. }
  83.  
  84. void YourProgram()
  85. {
  86. UserInfo user = new UserInfo();
  87. ...
  88.  
  89. // Bind propertygrid to object
  90.  
  91. grid.DataObject = NewUserInfo.GetNewUser(user);
  92.  
  93. ...
  94.  
  95. }
Add Comment
Please, Sign In to add comment