这应该真的返回一个空String()?

时间:2010-11-26 19:39:32

标签: vb.net inheritance attributes custom-attributes

我有一个属性类:

<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的值,因为我在{的继承参数中指定 True {1}}方法?

1 个答案:

答案 0 :(得分:2)

我认为有两个主要的混淆点:

  1. 您的代码正在查找某个类型的属性,并且这些属性将应用于属性。如果要检索属性,则需要在Login或Name等属性上查找它们。
  2. 无论如何,继承和实现之间存在差异。类Group 实现接口IGroup,因此当您在Group上请求继承的属性时,您将看不到IGroup上定义的任何属性。如果你想要一个类型实现的接口上的属性,你需要直接询问接口,你不能通过该类型。