所以我正在尝试使用新ISourceGenerator系统从 XML 文件中生成一些 I18n 字符串和类。这可行,但现在我想使用源生成器扩展现有的部分类,但每当我这样做时,原始类内容变得无法访问!这是我的课程:
// File: Strings.cs
namespace MyProject.I18n
{
public static partial class Strings
{
public const string Options = "Options";
}
}
这就是我正在生成的:
// Generated file: GeneratedStrings.cs
namespace MyProject.I18n
{
public static partial class Strings
{
public const string MainMenu = "Main menu";
}
}
这就是我生成它的方式(MVCE):
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
[Generator]
public class I18NGenerator : ISourceGenerator
{
private const string XML_EXAMPLE = @"
<Strings>
<MainMenu>Main menu</MainMenu>
</Strings>
";
private StringBuilder sb = null!;
private int indentation;
public void Initialize(GeneratorInitializationContext context)
{
sb = new StringBuilder();
indentation = 0;
}
public void Execute(GeneratorExecutionContext context)
{
var root = XDocument.Parse(XML_EXAMPLE).Root!;
void Process(XElement element)
{
var text = element.Nodes().FirstOrDefault(node => node is XText);
if (text is XText xText)
{
IndentedLn($@"public static string {element.Name.LocalName} = ""{xText.Value}"";");
}
else
{
BeginBlock($"public static partial class {element.Name.LocalName}");
foreach (var xElement in element.Elements())
Process(xElement);
EndBlock();
}
}
BeginBlock("namespace MyProject.I18n");
Process(root);
EndBlock();
context.AddSource("GeneratedStrings.cs", SourceText.From(sb.ToString(), Encoding.UTF8));
}
private void Indent()
{
indentation++;
}
private void Dedent()
{
indentation--;
}
private void BeginBlock(string statement = "")
{
if (statement.Length != 0)
IndentedLn(statement);
IndentedLn("{");
Indent();
}
private void EndBlock()
{
Dedent();
IndentedLn("}");
}
private void Raw(string text) => sb.Append(text);
private void Indented(string code)
{
for (var i = 0; i < indentation; i++)
Raw("\t");
Raw(code);
}
private void IndentedLn(string code) => Indented(code + "\n");
}
试图访问Strings.Options会产生编译错误'Strings' does not contain a definition for 'Options'。
我可以补充一点,如果我生成两个文件,它们合并得很好。