如何解决Roslyn 的 SyntaxReceiver - 获取实现接口的类
我正在尝试开发一个源代码生成器,以在具有该接口的部分类上自动实现一个接口。
我相信这必须是 Microsoft's new Source Generators 的一个常见用例,甚至在 Roslyn Source Generator Cookbook 中被列为用例,但没有示例实现。
我已经在 Roslyn Analyzers 中搜索过,但一直在努力寻找针对此场景的问题。
在说明书中,他们使用 SyntaxReceiver 类来过滤 Execute
调用应处理哪些语法节点:
class SluggableSyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> ClassesToAugment { get; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Business logic to decide what we're interested in goes here
if(syntaxNode is ClassDeclarationSyntax cds && cds.HasInterface("IChangeTracked"))
ClassesToAugment.Add(cds)
}
}
查看说明书以了解生成器的实现细节。
我想要确定的是如何在 ClassDeclarationSyntax 节点上实现我的 HasInterface
扩展。
public static bool HasInterface(this ClassDeclarationSyntax source,string interfaceName)
{
IEnumerable<TypeSyntax> baseTypes = source.BaseList.Types.Select(baseType=>baseType.Type);
// Ideally some call to do something like...
return baseTypes.Any(baseType=>baseType.Name==interfaceName);
}
我该怎么做:
- 从 ClassDeclarationSyntax 中获取 BaseList 属性,
- 确定类是否是部分类
- 访问接口
- 确定是否有任何接口属于特定类型。
解决方法
我必须相信有比我所做的更好的方法来做到这一点,但就其价值而言,这是一个确定特定 ClassDeclarationSyntax
是否显式实现接口的有效实现:
/// <summary>Indicates whether or not the class has a specific interface.</summary>
/// <returns>Whether or not the SyntaxList contains the attribute.</returns>
public static bool HasInterface(this ClassDeclarationSyntax source,string interfaceName)
{
IEnumerable<BaseTypeSyntax> baseTypes = source.BaseList.Types.Select(baseType => baseType);
// To Do - cleaner interface finding.
return baseTypes.Any(baseType => baseType.ToString() ==interfaceName);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。