获取在运行时修改的属性属性的运行时值

时间:2015-07-17 04:52:57

标签: c# .net reflection attributes

我试图获取在C#.NET 4.0中迄今为止没有任何运气的类中定义的属性的运行时值,该类已经在运行时修改。任何有关如何做到这一点的指南都将受到赞赏。

假设我有一个名为Test33的类,其中有一个名为DisplayTwoDecimals的属性,我在其上应用了Browsable(false)。稍后在代码中,我会将Browsable的值更新为true。我想检查Browsable属性在运行时的值是什么,我希望得到值true

以下是Test33类:

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;
    }
}

以下代码片段在富文本框中显示运行时Browsable属性的值:

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");
}

尽管我已将Browsable属性更改为true,但富文本框显示False

修改

不同,就像在运行时为属性设置一些值一样。

0 个答案:

没有答案
相关问题