C# SourceGenerators

一、生成代码项目.csproj配置,这里注意要选择netstandard2.0,这里以项目名,SourceGenerators.csproj为例:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
	  <TargetFramework>netstandard2.0</TargetFramework>
	  <LangVersion>latest</LangVersion>
	  <!-- 禁止输出主程序集(生成器本身不需要编译为可执行文件) -->
	  <IncludeBuildOutput>false</IncludeBuildOutput>
	  <!-- 标记为分析器项目 -->
	  <IsRoslynComponent>true</IsRoslynComponent>

	  <!-- 启用分析器严格规则(避免潜在问题) -->
	  <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>

	  <!-- 可选:输出生成的文件到指定目录(便于调试) -->
	  <!-- <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
	  <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath> -->
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" />
  </ItemGroup>

</Project>

二、主项目或其他需要使用代码生成项目的项目,在项目中要先引用SourceGenerators项目,引用后修改.csproj配置,这里以WPF.csproj主项目为例:

<ItemGroup>
  <ProjectReference Include="..\SourceGenerators.csproj" 
                  OutputItemType="Analyzer"
                  ReferenceOutputAssembly="false" />
</ItemGroup>

这里增加了 
OutputItemType="Analyzer" 
ReferenceOutputAssembly="false" 
注意,在引用项目后有可能不能立即生效,需要各项目根文件夹中删除bin和obj文件夹,然后重新生成项目。

****

#三、通过dll方式引用分析器dll

```csharp
//分析器项目.csproj配置
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
	  <TargetFramework>netstandard2.0</TargetFramework>
	  <LangVersion>latest</LangVersion>
	  <!-- 禁止输出主程序集(生成器本身不需要编译为可执行文件) -->
	  <!--<IncludeBuildOutput>false</IncludeBuildOutput>-->
	  <!-- 标记为分析器项目 -->
	  <IsRoslynComponent>true</IsRoslynComponent>

	  <!-- 启用分析器严格规则(避免潜在问题) -->
	  <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>

	  <!-- 可选:输出生成的文件到指定目录(便于调试) -->
	  <!-- <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
	  <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath> -->
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" />
  </ItemGroup>

</Project>

需要引用的项目.csproj配置:

  <ItemGroup>
		<Analyzer Include="..\DLLs\BridgeVision.Inventory.SourceGenerators.dll" />
  </ItemGroup>

若分析器项目引用了其他package包的dll,在主项目中引用nuget包,或者在.csproj配置:

  <Content Include="C:\Path\To\Dependencies\*.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
posted @ 2025-03-29 18:44  辰啸  阅读(103)  评论(0)    收藏  举报