我正在向.NET应用程序添加一个About对话框,并查询程序集的属性以获取要显示的信息。当我尝试使用GetCustomAttribute()检索程序集的AssemblyVersionAttribute时,它返回null
// Works fine
AssemblyTitleAttribute title
= (AssemblyTitleAttribute)Attribute.GetCustomAttribute(
someAssembly, typeof(AssemblyTitleAttribute));
// Gets null
AssemblyVersionAttribute version
= (AssemblyVersionAttribute)Attribute.GetCustomAttribute(
someAssembly, typeof(AssemblyVersionAttribute));我的AssemblyInfo.cs看起来没问题。我定义了以下属性:
[assembly: AssemblyTitle("Some Application")]
[assembly: AssemblyVersion("1.0.0.0")]怎么回事?我确实有一个解决办法,但我想知道为什么上面的代码不能工作。
// Work-around
string version = someAssembly.GetName().Version.ToString();发布于 2009-07-17 17:05:06
AssemblyVersionAttribute不会添加到程序集中,而是由编译器以“特殊”的方式处理(即,它设置程序集的版本)
您可以获取AssemblyFileVersion属性(即此属性被添加到程序集中)
还有其他显示相同行为的属性:AssemblyCultureAttribute和AssemblyFlagsAttribute也用于设置程序集属性,并且不会作为自定义属性添加到程序集中。
所有这些属性都列在文档中的程序集标识属性下。文档中对这些属性的描述如下:
三个属性与强名称(如果适用)一起确定程序集的标识:名称、版本和区域性。
发布于 2009-07-17 17:12:33
您的示例不是变通方法。这正是MSDN文档规定您应该做的,这让我相信代码是设计出来的。
http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx
若要获取已加载程序集的名称sic,请对该程序集调用
GetName以获取AssemblyName,然后获取Version属性。若要获取尚未加载的程序集的名称,请从客户端应用程序调用GetAssemblyName以检查应用程序使用的程序集版本。
发布于 2009-07-17 17:13:29
不知道为什么它会这样。我们不是针对AssemblyVersionAttribute,而是这样做:
Version AssemblyVersion = someAssembly.GetName().Version;对于AssemblyFileVersion,我们使用:
Version fileVersion = new Version("0.0.0.0");
AssemblyFileVersionAttribute[] fileVersionAttributes = (AssemblyFileVersionAttribute[])assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true);
if (fileVersionAttributes != null && fileVersionAttributes.Length > 0) {
fileVersion = new Version(fileVersionAttributes[0].Version);
}https://stackoverflow.com/questions/1144525
复制相似问题