.net - 如何使用 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)"
如何修改函数,使其自动检测主属性,或者使用提供的字符串参数作为属性名称?
解决方案
我找到了一个快速而肮脏的解决方案。但是,我希望看到任何其他可能的更好的解决方案。
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
推荐阅读
- python - 无法将字典合并到列表中
- php - Laravel 5.8 追随者系统错误“无消息”
- exe - 在 Windows 可执行文件中调用 az storage blob upload 命令失败并出现奇怪的异常
- python - Pygame鼠标点击更新?
- mysql - MYSQL:触发器仅在第一次调用 SP
- ios - 视图控制器所需的便利性导致的 Swift 错误
- angularjs - 如何使用 AngularJS 设置开发环境?我无法启动和运行基本的 AngularJS 应用程序
- php - 无法从 URL 重写中获取值
- pandas - 来自 pyspark 的数据集的多处理返回 JVM 错误
- graph-theory - 如何解决修正的旅行推销员问题?