1

我应该如何 a) 定义自定义属性和 b) 在以下场景中获取所述自定义属性分配?

场景:我们想定义一个自定义属性(custAtrib1)供继承类(基类(myBase)的myClassFoo使用。然后基类将检索分配给继承实例的自定义属性,然后执行一些操作。

问题:每当在基类中针对继承的类调用 GetCustomAttribute 时,GetCustomAttibutes 方法只返回一个结果(System.Runtime.CompilerServices.CompilerGlobalScopeAttribute)。

以下是属性/类的定义方式:

属性:(文件:myFoo.vb)

'-----------------------------------------------------------------
Namespace Foo.CustomAttributes

<System.AttributeUsage(AttributeTargets.Class, AllowMultiple:=True, inherited:=False)> _
Public Class custAttrib1
    Inherits System.Attribute

    Public Property myAttributeInto as String
End Namespace
'-----------------------------------------------------------------

基类:(文件:myBar.vb)

'-----------------------------------------------------------------
Namespace Foo.Bar
Public Class myBase

    Private Sub someCoolCode()
        Dim myInstanceType as Type = me.GetType()
        Dim custAttribs as Object() = myInstanceType.GetCustomAttributes(False)

        '-- at this time, only content of custAttribs array is System.Runtime.CompilerServices.CompilerGlobalScopeAttribute)
    End Sub

End Class
End Namespace
'-----------------------------------------------------------------

继承类:(文件:myBar2.vb)

'-----------------------------------------------------------------
Namespace Foo.Bar
<Foo.CustomAttributes.custAttrib1(myAttributeInfo:="Coding if fun")> _
Public Class myClassFoo 
      '-- other cool stuff goes there
    Public Sub inheritedMethod()
    End Sub
End Class
End Namespace
'-----------------------------------------------------------------

感谢您的帮助

4

1 回答 1

0

您的代码中唯一的问题是您没有从基类继承。否则,它可以正常工作。

下面是我用来测试的样例,包括错别字的继承和更正:

Public Class Form1

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        Dim oClass = New myClassFoo
        oClass.someCoolCode()

    End Sub

End Class

<System.AttributeUsage(AttributeTargets.Class, AllowMultiple:=True, inherited:=False)> _
Public Class custAttrib1
    Inherits System.Attribute

    Public Property myAttributeInfo As String
End Class

Public Class MyBaseClass

    Public Sub someCoolCode()
        Dim myInstanceType As Type = Me.GetType()
        Dim custAttribs As Object() = myInstanceType.GetCustomAttributes(False)

        '-- at this time, only content of custAttribs array is System.Runtime.CompilerServices.CompilerGlobalScopeAttribute)

        Debug.WriteLine(DirectCast(custAttribs(0), custAttrib1).myAttributeInfo)
    End Sub

End Class

<custAttrib1(myAttributeInfo:="Coding is fun")> _
Public Class myClassFoo
    Inherits MyBaseClass

    '-- other cool stuff goes there
    Public Sub inheritedMethod()
    End Sub
End Class
于 2015-08-04T00:15:28.990 回答