Setting value of BrowsableAttribute at runtime

2020-04-11 09:46发布

I wanted to set a value of BrowsableAttribute for some of MyClass instance's properties at runtime:

 public class MyClass
{
     [Browsable(true)]
     public int P1 { get; set } 
     ...
}

Please advise how it can be done as well as how to add BrowsableAttribute to a MyClass instance's property at runtime if this attribute doesn't exist.

3条回答
We Are One
2楼-- · 2020-04-11 10:09

You can implement a custom type descriptor - which intercepts the the attribute on the way to whatever is using it. Thus having an effect which looks like the attribute is changing.

See - Part 1, Part2

查看更多
神经病院院长
3楼-- · 2020-04-11 10:22

You sort of can. I'm trying something like this at the moment, which I managed to get working with CategoryAttribute. Currently though, this stops the propertiesgrid from working all together though, even though this is being called in the constructor of a button:

Dim PC As PropertyDescriptorCollection = TypeDescriptor.GetProperties(Me)
For i As Integer = 0 To PC.Count - 1
        Dim att As BrowsableAttribute = DirectCast(PC(i).Attributes(GetType(BrowsableAttribute)), BrowsableAttribute)
        If Not att Is Nothing Then
            If att.Browsable = True Then
                Dim cat As Reflection.FieldInfo = att.GetType.GetField("Browsable", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.IgnoreCase)
                If Not cat Is Nothing Then
                    cat.SetValue(att, False)
                End If
            End If
        End If
Next

Hope this helps

查看更多
Summer. ? 凉城
4楼-- · 2020-04-11 10:23

You can't - unless you intercept loading the assembly. The attributes are stored in metadata, and loaded with the assembly, and attributes should generally be immutable (as BrowsableAttribute is).

Basically attributes aren't meant to be modified at execution time.

查看更多
登录 后发表回答