【问题标题】:How to filter or find properties based on attributes如何根据属性过滤或查找属性
【发布时间】:2010-10-06 14:18:26
【问题描述】:

我有一堂课如下

Public Class Foo
    Private _Name As String
    <ShowInDisplay()> _
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Age As String
    Public Property Age() As String
        Get
            Return _Age
        End Get
        Set(ByVal value As String)
            _Age = value
        End Set
    End Property

    Private _ContactNumber As String
    <ShowInDisplay()> _
    Public Property ContactNumber() As String
        Get
            Return _ContactNumber
        End Get
        Set(ByVal value As String)
            _ContactNumber = value
        End Set
    End Property
End Class

我只需要处理那些具有特定属性的属性,例如:ShowInDisplay

Public Sub DisplayOnlyPublic(ByVal Someobject As Foo)
    For Each _Property As something In Someobject.Properties
        If _Property.HasAttribute("ShowInDisplay") Then  
           Console.WriteLine(_Property.Name & "=" & _Property.value)
        End If
    Next
End Sub

【问题讨论】:

    标签: .net vb.net reflection properties attributes


    【解决方案1】:

    编辑:更新为正确的 VB GetType() 调用:

    If _Property.IsDefined(GetType(ShowInDisplayAttribute), True) Then
    

    【讨论】:

    • If _property.IsDefined(GetType(ShowInDisplay), True) 那么再次感谢
    • 我只是想为其他人在 StackOverFlow 上建立一个关于反射的快速参考。感谢参与
    【解决方案2】:

    除了能够使用扩展方法/lambda(无论如何在 c# 中)使其更好之外,没有比在每个可用属性上使用 MemberInfo.IsDefined 更简单的方法了。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2018-10-10
      • 2015-05-30
      • 2015-10-13
      相关资源
      最近更新 更多