2009-02-10 103 views
0

我有一個類如下如何篩選或查找基於屬性的屬性

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 

回答

2

編輯:用正確的VB更新致電:

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

GetType()關鍵字! ;-) – Cerebrus 2009-02-10 08:12:49

0

除了可以使用擴展方法/ lambda表達式(無論在c#中)使用它更好之外,沒有比在每個可用屬性上使用MemberInfo.IsDefined更簡單的方法。