c# - RoslynCodeAnalysisService 编码时出现异常
问题描述
在将 VisualStudio 2019 与我自己的源代码生成器一起使用时。我在 Visual Studio 中遇到异常,它提示我打开调试器。
这只会在编码时发生,而不是在构建时发生(这让我认为我的源生成器很好)。
尝试调试时,我看到一个空白页并且调用堆栈没有任何信息。
我知道它必须链接到我的发电机,但我不知道如何。任何有关如何调试的提示将不胜感激。
完整的源代码可在此处获得:https ://github.com/kYann/StrongTypeId/tree/master/src/StrongType.Generators
[Generator]
public class StrongTypeIdGenerator : ISourceGenerator
{
Template template;
public void Initialize(GeneratorInitializationContext context)
{
var file = "StrongTypeId.sbntxt";
template = Template.Parse(EmbeddedResource.GetContent(file), file);
context.RegisterForSyntaxNotifications(() => new StrongTypeIdReceiver());
}
private string GenerateStrongTypeId(string @namespace, string className)
{
var model = new
{
Namespace = @namespace,
ClassName = className,
};
// apply the template
var output = template.Render(model, member => member.Name);
return output;
}
public bool IsStrongTypeId(INamedTypeSymbol recordSymbol)
{
var strongTypeIdType = typeof(StrongTypeId<>);
var originalBaseTypeDef = recordSymbol.BaseType.OriginalDefinition;
var baseTypeAssembly = originalBaseTypeDef.ContainingAssembly;
var isSameAssembly = baseTypeAssembly.ToDisplayString() == strongTypeIdType.Assembly.FullName;
var isSameTypeName = strongTypeIdType.Name == originalBaseTypeDef.MetadataName;
return isSameAssembly && isSameTypeName;
}
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not StrongTypeIdReceiver receiver)
return;
foreach (var rds in receiver.RecordDeclarations)
{
var model = context.Compilation.GetSemanticModel(rds.SyntaxTree);
if (model.GetDeclaredSymbol(rds) is not INamedTypeSymbol recordSymbol)
continue;
if (!IsStrongTypeId(recordSymbol))
continue;
var ns = recordSymbol.ContainingNamespace.ToDisplayString();
var output = GenerateStrongTypeId(ns, recordSymbol.Name);
// add the file
context.AddSource($"{recordSymbol.Name}.generated.cs", SourceText.From(output, Encoding.UTF8));
}
}
private class StrongTypeIdReceiver : ISyntaxReceiver
{
public StrongTypeIdReceiver()
{
RecordDeclarations = new();
}
public List<RecordDeclarationSyntax> RecordDeclarations { get; private set; }
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is RecordDeclarationSyntax rds &&
rds.BaseList is not null)
{
this.RecordDeclarations.Add(rds);
}
}
}
}
解决方案
RoslynCodeAnalysisService 有一个积极的缓存策略,并且将以前的源生成器保存在内存中。重新启动视觉工作室就可以了
推荐阅读
- python - 似乎不明白错误的原因
- regex - 为什么 sed 的正则表达式分组与普通正则表达式不同?
- amazon-web-services - 如何提高 AWS EC2 启动时间?
- reporting-services - 将一个超组的总和放入一个子组
- java - logging.properties 文件的存在会阻止写入日志
- sql-server - 给定 Azure 中 SQL 数据库上 SQL 查询的查询 ID,有没有办法返回并跟踪谁发起了查询?
- python - Python机器学习错误:期待整数
- linux - 如何保持输入 ansi 颜色编码的 grep?
- python - 由于 Django 中的“模板标签”而导致的空白页面
- sql - 选择 id 包含在另一个表字段中的项目