AssemblyInformationalVersion在运行时获取程序集属性值的C#语法是什么?例:
[assembly: AssemblyInformationalVersion("1.2.3.4")]
lan*_*nce 64
using System.Reflection.Assembly
using System.Diagnostics.FileVersionInfo
// ...
public string GetInformationalVersion(Assembly assembly) {
return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
}
Run Code Online (Sandbox Code Playgroud)
xan*_*tos 39
var attr = Assembly
.GetEntryAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
as AssemblyInformationalVersionAttribute[];
Run Code Online (Sandbox Code Playgroud)
这是一个阵列AssemblyInformationalVersionAttribute.即使没有搜索类型的属性,它也不会为空.
var attr2 = Attribute
.GetCustomAttribute(
Assembly.GetEntryAssembly(),
typeof(AssemblyInformationalVersionAttribute))
as AssemblyInformationalVersionAttribute;
Run Code Online (Sandbox Code Playgroud)
如果该属性不存在,则此值可以为null.
var attr3 = Attribute
.GetCustomAttributes(
Assembly.GetEntryAssembly(),
typeof(AssemblyInformationalVersionAttribute))
as AssemblyInformationalVersionAttribute[];
Run Code Online (Sandbox Code Playgroud)
与第一个相同.
Rob*_*eer 17
在应用程序中使用已知类型,您只需执行以下操作:
using System.Reflection;
public static readonly string ProductVersion = typeof(MyKnownType).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
Run Code Online (Sandbox Code Playgroud)
当然,您用于获取属性所应用的程序集的任何过程都是好的.请注意,这不依赖于System.DiagnosticsWinForm的Application对象.
wol*_*yst 13
即使这个问题有点旧:
我提出了一个适合我的不同解决方案:
Application.ProductVersion
Run Code Online (Sandbox Code Playgroud)
Geo*_*ung 13
public static string? GetInformationalVersion() =>
Assembly
.GetEntryAssembly()
?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
Run Code Online (Sandbox Code Playgroud)
虽然我的答案与其他一些人类似,但我认为它有一些优点:
GetEntryAssembly()为GetExecutingAssembly()GetCustomAttribute<T>并且认为这个变体更具可读性。另请参阅有关 的 Microsoft 文档GetCustomAttribute<T>(Assembly)。
请注意,在像 MAUI Android 这样的 illlink/AoT 场景中,这可能会返回 null。如果您使用自动版本控制解决方案,可能还有其他无反射方法来获取版本信息。例如,如果您正在使用Nerdbank.GitVersioning,您可以使用
public static string? GetInformationalVersion() =>
ThisAssembly.AssemblyInformationalVersion;
Run Code Online (Sandbox Code Playgroud)
AssemblyInformationalVersionAttribute attribute =
(AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault();
if (attribute != null)
Console.WriteLine(attribute.InformationalVersion);
Run Code Online (Sandbox Code Playgroud)
小智 5
为了补充lance的答案:您可以Application.ResourceAssembly.Location用来找出程序集的文件路径.有了这个,就可以将AssemblyInformationalVersion字符串放在一行中
System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ResourceAssembly.Location).ProductVersion
Run Code Online (Sandbox Code Playgroud)