【问题标题】:why can't I load the AssemblyVersion attribute using reflection?为什么我不能使用反射加载 AssemblyVersion 属性?
【发布时间】:2013-01-29 18:42:05
【问题描述】:

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

Attribute[] y = Assembly.GetExecutingAssembly().GetCustomAttributes();

我明白了:

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

然而我已经无数次检查了这个属性是否存在于我的代码中:

 [assembly: AssemblyVersion("5.5.5.5")]

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

Attribute x = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyVersionAttribute)); //exception

我想我将无法使用该属性,但 .NET 为何不读取它?

【问题讨论】:

  • 你想做什么? Assembly 已经有一个 Version 属性。
  • 你确定吗?我看不到具有该名称的静态或实例属性
  • 您将不得不使用GetName() 示例var y = Assembly.GetExecutingAssembly().GetName().Version;
  • [AssemblyVersion] 在 .NET 中非常重要。编译器特别对待属性,它在生成程序集的元数据时使用它。并且实际上并没有发出该属性,那将是两次。请改用 AssemblyName.Version,如图所示。

标签: c# .net exception reflection .net-assembly


【解决方案1】:

如果您只是想获得汇编版本,那非常简单:

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

属性是System.Version的一种类型,具有MajorMinorBuildRevision属性。

例如。 1.2.3.4 版本的程序集有:

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

【讨论】:

  • 奇怪的是我们无法使用反射获得 AssemblyVersionAttribute...
【解决方案2】:

(只是为了完善获得版本的味道......)

如果您尝试获取任意程序集的 文件 版本信息(即,不是一个已加载/正在运行的程序集),您可以使用 FileVersionInfo - 但是请注意,这可能不是元数据中指定的相同AssemblyVersion

var filePath = @"c:\path-to-assembly-file";
FileVersionInfo info = FileVersionInfo.GetVersionInfo(filePath);

// the following two statements are roughly equivalent
Console.WriteLine(info.FileVersion);
Console.WriteLine(string.Format("{0}.{1}.{2}.{3}", 
         info.FileMajorPart, 
         info.FileMinorPart, 
         info.FileBuildPart, 
         info.FilePrivatePart));

【讨论】:

  • 那是 [AssemblyFileVersion]。
  • @HansPassant 啊,好点; 文件版本和通过反射获得的“程序集”版本之间的潜在区别......尽管有人可能会说它们应该是相同的......:)跨度>
  • @JerKimball 我不同意他们需要相同。 Fileversion 不会导致程序集的绑定差异,如果您有一个已签名的程序集并且需要保持工作相同,您可以增加 Fileversion 并仍然允许旧项目使用“固定”程序集(具有相同的程序集版本)跨度>
  • @PaulFarry 实际上,这是一个非常的好点。你卖了我;我撤销了我的立场......好吧,不管我暗示的相反是什么。
【解决方案3】:

我将重复 Hans Passant 的评论:

[AssemblyVersion] 在 .NET 中非常重要。编译器特别对待属性,它在生成程序集的元数据时使用它。并且实际上并没有发出该属性,那将是两次。请改用 AssemblyName.Version,如图所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2021-06-04
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多