Roslyn Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Create a C# class library project, say ClassLibrary, in Visual Studio 2017.
  2. In solution explorer, right-click on the solution or project node and execute the Manage NuGet Packages command:
  1. This brings up the NuGet Package Manager, which can be used to search and install NuGet packages to the solution or project:
  1. In the search bar, type the following text to find NuGet packages tagged as analyzers : Tags:"analyzers".
Note that some of the well-known packages are tagged as analyzer, so you may also want to search for Tags:"analyzer" .
  1. Check or uncheck the Include prerelease checkbox to the right of the search bar to search or hide the pre-release analyzer packages, respectively. The packages are listed based on the number of downloads, with the highest downloaded package at the top:
  1. Select a package to install, say System.Runtime.Analyzers, and pick a specific version, say 1.1.0, and click on Install:
  1. Click on the I Accept button on the License Acceptance dialog to install the NuGet package.

 

  1. Verify the installed analyzer(s) that shows up under the Analyzers node in the solution explorer:
  1. Verify that the project file has a new ItemGroup with the following analyzer references from the installed analyzer package:
<ItemGroup>
<Analyzer Include="..\packages\System.Runtime.Analyzers.1.1.0\analyzers\dotnet\cs\System.Runtime.Analyzers.dll" />
<Analyzer Include="..\packages\System.Runtime.Analyzers.1.1.0\analyzers\dotnet\cs\System.Runtime.CSharp.Analyzers.dll" />
</ItemGroup>
  1. Add the following code to your C# project:
namespace ClassLibrary
{
public class MyAttribute : System.Attribute
{
}
}
  1. Verify the analyzer diagnostic from the installed analyzer that is shown in the error list:
  1. Open Developer Command Prompt for VS 2017 and build the project to verify that the analyzer is executed on the command-line build and that the analyzer diagnostic is reported:

  1. Create a new C# project in VS 2017 and add the same code to it as step 10. Verify that no analyzer diagnostic shows up in the error list or command line, confirming that the analyzer package was only installed to the selected project in steps 1-6.
Note that CA1018 ( the custom attribute should have AttributeUsage defined) has been moved to a separate analyzer assembly in future versions of the FxCop/System.Runtime.Analyzers package. It is recommended that you install the Microsoft.CodeAnalysis.FxCopAnalyzers NuGet package from ( https://www.nuget.org/packages/Microsoft.CodeAnalysis.FxCopAnalyzers)to get the latest group of Microsoft-recommended analyzers.