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

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

问题描述

我已经创建了一个自定义属性,并在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


推荐答案

您必须使用Reflection获取属性信息和值,并且每个属性都需要一个proc。

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

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

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 是Property getter的名称。因此,对于我添加的那个对象,将是:

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

Return Attributes(0).GetBuild

与获取类或枚举等的Attr大约相同。此外:程序集已经具有版本,因此您可以在Project属性中进行控制设置。并且procs已经存在于 System.Reflection 中以返回它们。

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

或命名我的proc 版本补丁

or name my proc VersionPatch

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

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