【问题标题】:Should this really return an empty String()?这真的应该返回一个空的 String() 吗?
【发布时间】:2011-05-16 08:17:15
【问题描述】:

我有一个属性类:

<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

话虽如此,既然我在Type.GetCustomAttributes 方法的继承参数中指定了TruePrivate Property Attributes() As String() 是否也不会返回放置在接口属性上的DirectoryAttribute 的值?

【问题讨论】:

标签: vb.net inheritance attributes custom-attributes


【解决方案1】:

我认为主要有两点混淆:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2021-02-07
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多