1

我有一個屬性類:這應該真的返回一個空的String()嗎?

<AttributeUsage(AttributeTargets.Property)> _ 
Public Class DirectoryAttribute 
    Inherits Attribute 

    Private _attribute As String 

    Public Sub New(ByVal attribute As String) 
     _attribute = attribute 
    End Sub 

    Public ReadOnly Property Attribute As String 
     Get 
      Return _attribute 
     End Get 
    End Property 
End Class 

和接口和類:

Public Interface IDirentoryEntity 
    <DirectoryAttribute("Name")> _ 
    Property Name As String 
End Interface 

Public Interface IOrganizationalUnit 
    Inherits IDirectoryEntity 
End Interface 

Public Class OrganizationalUnit 
    Implements IOrganizationalUnit 

    ' Implementing IOrganizationalUnit here...' 
End Class 

Public Interface IIdentifiableDirectoryEntity 
    Inherits IDirectoryEntity 

    <DirectoryAttribute("sAMAccountName")> _ 
    Property Login As String 
End Interface 

Public Interface IGroup 
    Inherits IIdentifiableDirectoryEntity 
End Interface 

Public Class Group 
    Implements IGroup 

    Private _attributes() As String 

    ' Implementing IGroup here...' 

    Private ReadOnly Property Attributes() As String() 
     Get 
      If (_attributes Is Nothing) Then 
       Dim attr() As DirectoryAttribute = _ 
        CType(GetType(Group).GetCustomAttributes(GetType(DirectoryAttribute), True), DirectoryAttribute()) 

       If (attr Is Nothing OrElse attr.Length = 0 OrElse attr(0) Is Nothing) Then _ 
        Return New String(0) { } 

       _attributes = New String(attr.Length) { } 

       For index As Integer = 0 To attr.Length - 1 Or _attributes.Length - 1 Step 1 
        _attributes(index) = attr(index).Attribute 
       Next 
      End If 

      Return _attributes 
     End Get 
    End Property 
End Class 

隨着中說,應在Private Property Attributes() As String()不會返回放置在接口性能好,的DirectoryAttribute值,因爲我在Type.GetCustomAttributes方法的繼承參數中指定True

+0

http://hyperthink.net/blog/getcustomattributes-gotcha/ – 2010-11-26 19:51:01

回答

2

我認爲有混淆的兩個要點:

在類型
  1. 您的代碼查找屬性,而屬性應用於性能。如果你想檢索屬性,你需要在Login或Name等屬性上查找它們。
  2. 無論如何,繼承和實現之間是有區別的。該類組實現了接口IGroup,因此當您要求繼承屬性時,您將看不到在IGroup上定義的任何屬性。如果你想要一個類型實現的接口的屬性,你需要直接詢問接口,你不能通過類型。
相關問題