调用自定义程序集属性 [英] Calling Custom Assembly Attributes

查看:28
本文介绍了调用自定义程序集属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义属性并在 AssemblyInfo.vb 文件中使用它.该属性在另一个文件中声明如下:

I have created a custom attribute and use it in the AssemblyInfo.vb file. The attribute is declared in another file like so:

Public NotInheritable Class AssemblyBuildNameAttribute
    Inherits Attribute

    Private _p1 As String

    Sub New(p1 As String)
        ' TODO: Complete member initialization 
        _p1 = p1
    End Sub

End Class

并且在 AssemblyInfo.vb 文件中如下所示:

And is in the AssemblyInfo.vb file like so:

<Assembly: AssemblyVersion("0.4.15")> 
<Assembly: AssemblyFileVersion("13.10.1.8")> 
<Assembly: AssemblyBuildName("alpha")>

我该如何调用这个自定义属性??我希望能够像这样调用版本信息一样调用它:

How can I call this custom attribute?? I would like to be able to call it just like I call the version information like so:

Public Class AppInfo
  Public Shared Function VersionMajor() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Major.ToString()
  End Function
  Public Shared Function VersionMinor() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString()
  End Function
  Public Shared Function VersionPatch() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Build.ToString()
  End Function
End Class

推荐答案

必须使用反射来获取属性信息和值,并且每个属性都需要一个 proc.

You have to use Reflection to get attribute information and value, and you will need one proc for each attribute.

首先,您的示例属性类缺少一个关键项:如何返回信息.您需要添加一个属性 getter:

First though, your sample Attribute class is missing a key item: HOW TO RETURN the info. You need to add a property getter:

Friend ReadOnly GetBuild() As String
   Get
      Return _p1
   End Get
End Property

现在你准备好了

Friend Function GetAsmBuild() As String
    Dim assy As [Assembly] = [Assembly].GetExecutingAssembly
    Dim Attributes As Object()


    Attributes = assy.GetCustomAttributes(GetType(AssemblyBuildNameAttribute), False)
    If Attributes.Length > 0 Then
        Return Attributes(0).GetBuild
    Else
       Return String.Empty
    End If

 End Function

GetVersion 是属性 getter 的名称.所以对于我添加的那一个:

GetVersion is the name of the Property getter. So for the one I added it would be:

Return Attributes(0).GetBuild

这与获取类或枚举等的 Attr 大致相同.此外:程序集已经有一个版本,因此您可以在项目属性设置中进行控制.并且 System.Reflection 中已经存在 proc 来返回它们.

It is about the same as getting Attr for Classes or Enums etc. Also: Assemblies already have a version and such you can control in the Project properties settings. And procs already exist in System.Reflection to return them.

运行时获取信息的方式:

The way to get the info at runtime:

Public Shared Function VersionPatch() As String
    Return GetAsmBuild
 End Function

或命名我的过程 VersionPatch

这篇关于调用自定义程序集属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆