我创建了以下项目
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处于活动状态