I'm trying to get the runtime value of a property defined in a class without any luck so far in C# .NET 4.0. Any guideline about how to do that would be appreciated.
Lets say I have a class named Test33
which has a property named DisplayTwoDecimals
on which I applied Browsable(false)
. Later in the code I will update the value of Browsable
to true
. I'd like to inspect what the value of Browsable
attribute is at runtime.
Here is the Test33
class:
public class Test33
{
[Browsable(false)]
public bool DisplayTwoDecimals
{
get; set;
}
public void ChangeBrowsableAttribute(bool value, string property)
{
PropertyDescriptor pDesc = TypeDescriptor.GetProperties(GetType())[property];
BrowsableAttribute attrib = (BrowsableAttribute)pDesc.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrowsable = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
isBrowsable.SetValue(attrib, value);
}
public static bool GetBrowsable(PropertyInfo property)
{
var atts = property.GetCustomAttributes(typeof(BrowsableAttribute), true);
if (atts.Length == 0)
return true;
return (atts[0] as BrowsableAttribute).Browsable;
}
}
Following code fragment shows the value of Browsable
attribute at runtime in a rich text box:
public Form1()
{
InitializeComponent();
Test33 t = new Test33();
t.ChangeBrowsableAttribute(true, "DisplayTwoDecimals");
List<PropertyInfo> pis = t.GetType().GetProperties().ToList();
richTextBox1.AppendText(Test33.GetBrowsable(pis[0]).ToString() + "\n");
}
Despite the face that I've changed the Browsable
attribute to true, the rich text box is showing False
.
Aucun commentaire:
Enregistrer un commentaire