【问题标题】:Read custom assembly attribute读取自定义程序集属性
【发布时间】:2013-04-16 23:45:21
【问题描述】:

我为 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

AssemblyInfo.vb:

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

获取另一个项目中的属性(通过变量:文件名)

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.InvalidCastException”

【问题讨论】:

  • 如果你Dim at As Object = att,去掉演员表,调试时att 是什么样子的?
  • 更改后“at”-Var 变为System.Reflection.AssemblyCompanyAttribute
  • 应该都是从System.Attribute派生出来的,有很多操作。您应该能够从中获取自定义属性。见msdn.microsoft.com/en-us/library/system.attribute.aspx的方法和例子。

标签: vb.net attributes .net-assembly


【解决方案1】:

问题的解决方案供未来访问者使用:

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

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

信息:

非常感谢@DanVerdolino 的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多