读取自定义程序集属性



我为DLL定义了以下程序集属性,但我无法在不同的项目中读取它。你有什么建议吗?

组装属性:

    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

进行标识:

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

获取另一个项目的属性(通过变量: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

在调试器中,我只得到很多"System. exe"。InvalidCastException "

为未来访客提供的问题解决方案:

  1. 你可以定义一个自定义的程序集属性,就像我在上面的问题中所做的那样。

  2. 要读取自定义属性,您可以使用System.Attribute.GetCustomAttributes()来获取所有定义属性的数组。但是你也可以使用System.Attribute.GetCustomAttribute()来获取你传递的类型的特定属性。

信息:

  • 系统。属性:http://msdn.microsoft.com/en-us/library/system.attribute.aspx
  • GetCustomAttribute (): http://msdn.microsoft.com/en-us/library/k7s8054x.aspx

非常感谢 @DanVerdolino的帮助!

相关内容

最新更新