简体   繁体   中英

Read custom assembly attribute

I defined the following Assembly Attribute for a DLL but I am not able to read it out in a different Project. Do you have any suggestions?

Assembly attribute:

    Namespace Extensions.CustomAttributes

    <AttributeUsage(AttributeTargets.All, Inherited:=True, AllowMultiple:=True)>

    Public Class DeveloperNoteAttribute
        Inherits System.Attribute

        Protected strName, strComment As String
        Protected blnBug As Boolean

        Public Sub New(ByVal Name As String, ByVal Comment As String, ByVal DateRecorded As String)
            MyBase.New()
            strName = Name
            strComment = Comment
        End Sub

        Public Property Name As String
            Get
                Return strName
            End Get
            Set(ByVal value As String)
                strName = value
            End Set
        End Property

        Public Property Comment As String
            Get
                Return strComment
            End Get
            Set(ByVal value As String)
                strComment = value
            End Set
        End Property

        Public Property Bug As Boolean
            Get
                Return blnBug
            End Get
            Set(ByVal value As Boolean)
                blnBug = value
            End Set
        End Property

    End Class

End Namespace

AssemblyInfo.vb:

<Assembly: Extensions.CustomAttributes.DeveloperNoteAttribute("Test1", "Test2", "Test3")> 

Get attributes in another project (via Variable: Filename)

Dim oAssem As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom(Filename)

' Get any assembly-level attributes
Dim oAttribs() As Attribute = Attribute.GetCustomAttributes(oAssem)
For Each att In oAttribs
   Try
        Dim at As Extensions.CustomAttributes.DeveloperNoteAttribute = CType(att, Extensions.CustomAttributes.DeveloperNoteAttribute)
        Debug.WriteLine(at.Name.ToString)
    Catch ex As Exception

    End Try
Next

In the debugger I just get a lot of "System.InvalidCastException"

The solution of the problem for future visitors:

  1. You can define a custom Assembly Attribute like I did in my question above.

  2. To read out the custom Attribute, you can use the System.Attribute.GetCustomAttributes() to get an Array of all the defines Attributes. But you can also use System.Attribute.GetCustomAttribute() which gets you a specific Attribute of the Type you passed.

Info:

Big Thanks to @DanVerdolino for his Help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM