我创建了以下项目

ClassLibrary1.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
    <Nullable>enable</Nullable>
    <LangVersion>10</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis" Version="4.6.0" />
  </ItemGroup>

</Project>

Class1.cs

using System;

namespace ClassLibrary1;

public static partial class Class1
{
    public static string GetS(string s)
    {
        var x = GetS2(s);

        return x ?? throw new InvalidOperationException();
    }

    private static partial string? GetS2(string s); // Error
}

SourceGenerator.cs

using Microsoft.CodeAnalysis;
using System.Text;

namespace ClassLibrary1;

[Generator]
public class SourceGenerator : ISourceGenerator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var sb = new StringBuilder();
        sb.AppendLine("namespace ClassLibrary1;");
        sb.AppendLine("public static partial class Class1");
        sb.AppendLine("{");
        sb.AppendLine("    private static partial string? GetS2(string s)");
        sb.AppendLine("    {");
        sb.AppendLine("        return \"Test\";");
        sb.AppendLine("    }");
        sb.AppendLine("}");

        context.AddSource("Class1.g.cs", sb.ToString());
    }

    public void Initialize(GeneratorInitializationContext context)
    {
    }
}

但是,它得到了以下错误?

错误CS8795分部方法‘Class1.GetS2(字符串)’必须有实现部分,因为它有可访问性修饰符.类库1 C:\source\repos\SourceGeneratorIssue\ClassLibrary1\Class1.cs 14处于活动状态

推荐答案

是的,所有三个文件都在一个项目中

您需要生成测试项目以运行源代码生成器,并且需要为要生成的项目运行源代码生成器.将源生成器移动到单独的项目中,并将其添加为引用:

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

此外,源代码生成器库必须以netstandard2.0为目标.从Source Generators overview doc:

源生成器项目需要以netstandard2.0TFM为目标,否则它将无法工作.

Csharp相关问答推荐

如何使用FastEndpoints和.NET 8 WebAppliationBuilder进行集成测试?

MongoDB将JS查询转换为C#的问题

哪个nuget包含SecurityStampValidatorOptions

ASP.NET MVC中创建视图的过滤器

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

如何告诉自己创建的NuGet包在应用程序中发生了变化?

TDLib与机器人共享电话号码

如何在C#中使用正则表达式抓取用逗号分隔的两个单词?

Blazor服务器端的身份验证角色

Rx.Net窗口内部可观测数据提前完成

如何使用MoQ模拟Resources GroupCollection?

.NET 8 DI GetServices<;对象&>不工作

为什么方法的值在SELECT方法中不会更改?

实体框架-IsRequired()与OnDelete()

如何在特定环境中运行dotnet测试?

如何使用类似于[SELECT*FROM&Q;&Q;WHERE&Q;]SQL查询的System.Data.Entity创建查询?

EF Core 7-忽略模型绑定中的虚拟属性

并发表更新.EF核心交易

根据优先级整理合同列表

如何在Cake脚本中设置MSBuild.exe的绝对路径