作者: zyl910
一、缘由
当创建 .NET Core/Standard 2.0项目时,VS不会像.NET Framework项目一样自动生成AssemblyInfo.cs文件。
而且,若是手工在项目中加入以前写好的 AssemblyInfo.cs 文件,编译时会报告“CS0579: Duplicate 'AssemblyFileVersionAttribute' attribute”错误。
查了一下资料,发现是因为“.NET Core/Standard 2.0会自动填写程序集信息”而引起的。
具体来说——
- .NET Core/Standard 2.0 推荐在项目属性的“Package”页配置程序集的 版本、描述 等信息。
- 编译时,会自动根据“Package”页的配置,生成 “.AssemblyInfo.cs”。其中便使用了 AssemblyFileVersionAttribute 等特性。
- 我们的 AssemblyInfo.cs 中也使用 AssemblyFileVersionAttribute 等特性。因为 AssemblyFileVersionAttribute 等特性是不允许重复,于是便报出CS0579错误了。
删除自己的 AssemblyInfo.cs,完全使用推荐做法(项目属性的“Package”页),当然是可以解决该问题、使项目能成功编译的。但是该方案的缺点是没有AssemblyInfo.cs,无法再用“利用条件编译控制程序集特性”等技巧。
第二种办法是在 AssemblyInfo.cs 中加上条件编译,若发现是 .NET Core/Standard 2.0(#if NETCOREAPP2_0 || NETSTANDARD2_0)时,便屏蔽掉 AssemblyFileVersionAttribute 等特性。但该方法比较繁琐。
有没有办法“禁止自动生成程序集特性,完全使用自己的AssemblyInfo.cs”呢?
二、解决
查了一下资料,找到了“.NET Core/Standard 2.0 禁止自动生成程序集特性”的办法。就是——修改项目的csproj文件,在PropertyGroup节点内加上“false”
例如修改前是这样的——
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>ConsoleExample</AssemblyName>
<RootNamespace>ConsoleExample</RootNamespace>
</PropertyGroup>
</Project>
修改后变为这样——
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>ConsoleExample</AssemblyName>
<RootNamespace>ConsoleExample</RootNamespace>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
</Project>
改好后便会发现不再自动生成 “.AssemblyInfo.cs”了,能使用自己的AssemblyInfo.cs,顺利编译了。
三、深入
3.1 自动生成的机制
“.AssemblyInfo.cs”的内容一般是这样的——
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("ConsoleExample")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("ConsoleExample")]
[assembly: System.Reflection.AssemblyTitleAttribute("C