1

J'ai une classe d'attributs:Cela devrait-il vraiment renvoyer une chaîne vide()?

<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 

interfaces et classes:

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 

Cela dit, ne l'Private Property Attributes() As String() pas retourner les valeurs de DirectoryAttribute placées sur les propriétés des interfaces aussi bien, puisque je spécifiez True dans le paramètre d'héritage de la méthode Type.GetCustomAttributes?

+0

http://hyperthink.net/blog/getcustomattributes-gotcha/ –

Répondre

2

Je pense qu'il ya deux points principaux de confusion:

  1. Votre code est à la recherche des attributs sur un type, et les attributs sont appliqués aux propriétés. Si vous souhaitez récupérer l'attribut, vous devez les rechercher sur une propriété, telle que Login ou Name. Quoi qu'il en soit, il y a une différence entre l'héritage et l'implémentation. Le groupe de classes implémente l'interface IGroup, donc vous ne verrez aucun attribut défini sur IGroup apparaître lorsque vous demandez hérités attributs sur le groupe. Si vous voulez des attributs sur une interface qu'un type implémente, vous devrez poser directement des questions sur l'interface, vous ne pouvez pas passer par le type.
Questions connexes