提问人:Enrico 提问时间:9/24/2023 更新时间:9/24/2023 访问量:63
Visual Studio 忽略源生成器
Source generator is ignored by Visual Studio
问:
我花了一整天的时间尝试在 Visual Studio 2022 中运行源生成器。我下载了一些源代码,但没有一个可以正常工作。Microsoft的例子都不是。我试图使用代码从域类创建 DTO。
因此,我基于并添加了这个类(来自 Microsoft 文档的代码)创建了一个简单的项目ClassLibrary1
NETStandard 2.1
CustomGenerator
)
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Text;
namespace ClassLibrary1
{
[Generator]
public class CustomGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context) { }
public void Execute(GeneratorExecutionContext context)
{
context.AddSource("myGeneratedFile.cs", SourceText.From(@"
namespace GeneratedNamespace
{
public class GeneratedClass
{
public static void GeneratedMethod()
{
// generated code
}
}
}", Encoding.UTF8));
}
}
}
然后,在另一个 NET7 项目中,我添加了 作为参考。我手动更改了项目,结果是ClassLibrary1
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<ProjectReference Include="..\DtoGenerator\DtoGenerator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>
我生成并重新生成了解决方案,并重新启动了 Visual Studio。结果是源生成器被忽略。
这个项目是这样的ClassLibrary1
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.7.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers"
Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp"
Version="4.7.0" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>
true
</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>
Generated
</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
答: 暂无答案
评论
netstandard2.0
netstandard2.0