如何解决使用源生成器生成部分类会删除原始类
所以我正在尝试使用新的 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'
。
我可以补充一点,如果我生成两个文件,它们合并就好了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。