Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Attribute's parameter at runtime

I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class

public class UserInfo {     [Category("change me!")]     public int Age     {         get;         set;     }     [Category("change me!")]     public string Name     {         get;         set;     } } 

This is a class that is provided by a third party vendor and I can't change the code. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.

May I know how to do this?

like image 660
Graviton Avatar asked Sep 09 '08 05:09

Graviton


1 Answers

Well you learn something new every day, apparently I lied:

What isn’t generally realised is that you can change attribute instance values fairly easily at runtime. The reason is, of course, that the instances of the attribute classes that are created are perfectly normal objects and can be used without restriction. For example, we can get the object:

ASCII[] attrs1=(ASCII[])     typeof(MyClass).GetCustomAttributes(typeof(ASCII), false); 

…change the value of its public variable and show that it has changed:

attrs1[0].MyData="A New String"; MessageBox.Show(attrs1[0].MyData); 

…and finally create another instance and show that its value is unchanged:

ASCII[] attrs3=(ASCII[])     typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);  MessageBox.Show(attrs3[0].MyData); 

http://www.vsj.co.uk/articles/display.asp?id=713

like image 150
Glenn Slaven Avatar answered Oct 06 '22 01:10

Glenn Slaven