为什么我无法使用反射来加载AssemblyVersion属性?
AssemblyInfo.cs文件具有的AssemblyVersion属性,但是当我运行以下命令:为什么我无法使用反射来加载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如何不读它呢?
我会重复汉斯帕桑特的评论:
[的AssemblyVersion]在.NET中真正的大事。编译器专门处理属性,它在生成程序集的元数据时使用它。并没有真正发出属性,那会做两次。如图所示,改用AssemblyName.Version。
如果你想只得到程序集的版本,这是很简单的:
Console.WriteLine("The version of the currently executing assembly is: {0}", Assembly.GetExecutingAssembly().GetName().Version);
该物业是一个类型的System.Version,其中有Major
,Minor
,Build
和Revision
性能。
例如,的1.2.3.4
版本的组件有:
-
Major
=1
-
Minor
=2
-
Build
=3
-
Revision
=4
(只是为了圆了得到一个的口味版本...)
如果你试图让一个任意组装文件版本信息(即不是一个加载/运行),您可以使用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]。 – 2013-02-14 02:40:07
@HansPassant啊,好点; *有*潜在的区别文件版本和通过反思得到的“大会”版本......虽然人们可能会争辩说他们*应该*是相同的...... :) – JerKimball 2013-02-14 02:44:05
@JerKimball我不同意他们需要一样。 Fileversion不会对程序集产生任何绑定差异,如果您拥有签名的程序集并需要保持相同的工作,则可以增加Fileversion并允许较早的项目使用“固定”程序集(使用相同程序集版本) – 2013-02-14 04:51:36
你想做什么? 'Assembly'已经有'Version'属性。 – ashes999 2013-02-14 02:17:51
你确定吗?我不会看到这个名字的静态和实例属性 – 2013-02-14 02:21:47
您将不得不使用'GetName()'示例'var y = Assembly.GetExecutingAssembly()。GetName()。Version;' – 2013-02-14 02:26:07