I want to create a helper function, that takes a AssemblyCustomAttribute type and returns the property value as string.
Here is the function code:
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
Is there any possiblity, that I can identify the primary property of the AssemblyCustomAttribute and return it as a string while option strict is on (no late bindings)?
The code above has the flaw, that it currently only supports the AssemblyConfigurationAttribute.
The second issue is that it has to work with .NET Framework 2.0. That is why there is not OfType<>
call, because it does not exists with 2.0.
For reference, I want to get the following attributes from AssemblyInfo.vb
<Assembly: AssemblyConfiguration("Debug")>
<Assembly: AssemblyInformationalVersion("1.0.0")>
with the following function calls:
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)"
How to modify the function, so it will automatically detect the primary property , or to use a supplied string parameter as the property name?
I found a quick and dirty solution. However, I would like to see any other possible better solution.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.