简体   繁体   English

调用自定义程序集属性

[英]Calling Custom Assembly Attributes

I have created a custom attribute and use it in the AssemblyInfo.vb file. 我创建了一个自定义属性,并在AssemblyInfo.vb文件中使用它。 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

And is in the AssemblyInfo.vb file like so: 并位于AssemblyInfo.vb文件中,如下所示:

<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

You have to use Reflection to get attribute information and value, and you will need one proc for each attribute. 您必须使用Reflection来获取属性信息和值,并且每个属性都需要一个proc。

First though, your sample Attribute class is missing a key item: HOW TO RETURN the info. 不过,首先,您的示例Attribute类缺少一个关键项:如何返回信息。 You need to add a property getter: 您需要添加一个属性获取器:

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

NOW you are ready 现在你准备好了

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 is the name of the Property getter. GetVersion是属性获取器的名称。 So for the one I added it would be: 因此,对于我添加的那是:

Return Attributes(0).GetBuild

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. 它与获取类或枚举等的Attr大约相同。另外:程序集已有版本,您可以在Project属性设置中进行控制。 And procs already exist in System.Reflection to return them. 并且procs已经存在于System.Reflection以返回它们。

Edit: 编辑:

The way to get the info at runtime: 在运行时获取信息的方法:

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

or name my proc VersionPatch 或命名我的proc VersionPatch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM