为什么我不能使用反射加载AssemblyVersion属性?

Joh*_*ith 7 .net c# reflection exception .net-assembly

assemblyinfo.cs文件具有AssemblyVersion属性,但是当我运行以下命令时:

Attribute[] y = Assembly.GetExecutingAssembly().GetCustomAttributes();
Run Code Online (Sandbox Code Playgroud)

我明白了:

System.Runtime.InteropServices.ComVisibleAttribute
System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
System.Runtime.CompilerServices.CompilationRelaxationsAttribute
System.Runtime.InteropServices.GuidAttribute

System.Diagnostics.DebuggableAttribute

System.Reflection.AssemblyTrademarkAttribute
System.Reflection.AssemblyCopyrightAttribute
System.Reflection.AssemblyCompanyAttribute
System.Reflection.AssemblyConfigurationAttribute
System.Reflection.AssemblyFileVersionAttribute
System.Reflection.AssemblyProductAttribute
System.Reflection.AssemblyDescriptionAttribute
Run Code Online (Sandbox Code Playgroud)

然而,我已无数次检查过我的代码中存在此属性:

 [assembly: AssemblyVersion("5.5.5.5")]
Run Code Online (Sandbox Code Playgroud)

...如果我尝试直接访问它,我会得到一个例外:

Attribute x = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyVersionAttribute)); //exception
Run Code Online (Sandbox Code Playgroud)

我想我将无法使用该属性,但是.NET怎么没有读它呢?

ash*_*999 9

如果您正试图获得程序集版本,那么它非常简单:

Console.WriteLine("The version of the currently executing assembly is: {0}", Assembly.GetExecutingAssembly().GetName().Version);
Run Code Online (Sandbox Code Playgroud)

的属性是一个类型的System.Version,其具有Major,Minor,Build,和Revision特性.

例如.一个版本的程序集1.2.3.4有:

  • Major = 1
  • Minor = 2
  • Build = 3
  • Revision = 4


Joh*_*ith 4

我将重复汉斯·帕桑特的评论:

[AssemblyVersion] 在 .NET 中确实是一件大事。编译器会特殊对待该属性,它在生成程序集的元数据时使用它。并且实际上并没有发出该属性,这会执行两次。请改用 AssemblyName.Version,如图所示。