首页 > 解决方案 > 如何使用 VB.NET 应用程序动态获取 AssemblyCustomAttribute 的值?

问题描述

我想创建一个辅助函数,它采用 AssemblyCustomAttribute 类型并将属性值作为字符串返回。

这是功能代码:

Public Shared Function GetAssemblyAttribute(tAttribute As Type, Optional bFirstResult As Boolean = True) As String
    Dim sRetVal As String = String.Empty

    Dim objAssembly As Assembly = Assembly.GetExecutingAssembly()
    Dim objAttributes As Object() = objAssembly.GetCustomAttributes(True)
    For Each objAttribute In objAttributes
        If objAttribute.GetType().Equals(tAttribute) Then
            sRetVal = objAttribute.Configuration
            If bFirstResult Then
                Exit For
            End If
        End If
    Next

    Return sRetVal
End Function

是否有任何可能性,我可以识别 AssemblyCustomAttribute 的主要属性并将其作为字符串返回,同时选项 strict 处于打开状态(没有后期绑定)?

上面的代码有一个缺陷,它目前只支持 AssemblyConfigurationAttribute。

第二个问题是它必须与 .NET Framework 2.0 一起使用。这就是为什么没有OfType<>调用,因为它在 2.0 中不存在。

作为参考,我想从中获取以下属性AssemblyInfo.vb

<Assembly: AssemblyConfiguration("Debug")>
<Assembly: AssemblyInformationalVersion("1.0.0")>

使用以下函数调用:

Me.lblAppVersion.Text = String.Format(
    "Version {0} ({1})",
    Helper.GetAssemblyAttribute((New System.Reflection.AssemblyConfigurationAttribute("")).GetType()),
    Helper.GetAssemblyAttribute((New System.Reflection.AssemblyInformationalVersionAttribute("")).GetType())
)
' Returns: "Version 1.0.0 (Debug)"

如何修改函数,使其自动检测主属性,或者使用提供的字符串参数作为属性名称?

标签: .netvb.net.net-assembly

解决方案


我找到了一个快速而肮脏的解决方案。但是,我希望看到任何其他可能的更好的解决方案。

Public Shared Function GetAssemblyAttribute(tAttribute As Type, Optional bFirstResult As Boolean = True) As String
    Dim sRetVal As String = String.Empty
    Dim objAssembly As Assembly = Assembly.GetExecutingAssembly()
    Dim objAttributes As Object() = objAssembly.GetCustomAttributes(True)
    For Each objAttribute In objAttributes
        If objAttribute.GetType().Equals(tAttribute) Then
            For Each objProperty In objAttribute.GetType().GetProperties()
                If objProperty.Name <> "TypeId" Then
                    sRetVal = objProperty.GetValue(objAttribute, Nothing)
                    If bFirstResult Then
                        Exit For
                    End If

                End If
            Next
        End If
    Next
    Return sRetVal
End Function

推荐阅读