使用 Roslyn SyntaxGeneration 生成带有声明的模式匹配
Posted
技术标签:
【中文标题】使用 Roslyn SyntaxGeneration 生成带有声明的模式匹配【英文标题】:Generate Pattern Matching with Declaration using Roslyn SyntaxGeneration 【发布时间】:2021-10-08 16:48:36 【问题描述】:我正在编写自定义代码重构以将变量声明转换为模式匹配表达式包括声明。这很好用,但我无法让声明部分工作。
我成功将MyOwnClass myClass = GetCustomClass();
转化为:
if(GetCustomClass() is MyOwnClass)
我无法将MyOwnClass myClass = GetCustomClass();
转换为:
if(GetCustomClass() is MyOwnClass myClass)
我的代码:
摘录:
var generator = SyntaxGenerator.GetGenerator(document);
SyntaxNode isTypeExpression = generator.IsTypeExpression(method, type);
SyntaxNode ifClause = generator.IfStatement(isTypeExpression, new List<SyntaxNode>(), new List<SyntaxNode>());
editor.ReplaceNode(localDeclartionSyntax, ifClause);
完整代码:
private async Task<Document> MakePatternMatchingClause(Document document, LocalDeclarationStatementSyntax localDeclartionSyntax, CancellationToken c)
if (document.TryGetSyntaxRoot(out SyntaxNode root))
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
var declaration = localDeclartionSyntax.Declaration;
var variableDeclarationSyntax = localDeclartionSyntax.Declaration.Variables.FirstOrDefault();
TypeSyntax type = localDeclartionSyntax.Declaration.Type;
var method = variableDeclarationSyntax.Initializer.Value;
SyntaxToken identifier = variableDeclarationSyntax.Identifier;
var generator = SyntaxGenerator.GetGenerator(document);
SyntaxNode isTypeExpression = generator.IsTypeExpression(method, type);
SyntaxNode ifClause = generator.IfStatement(isTypeExpression, new List<SyntaxNode>(), new List<SyntaxNode>());
editor.ReplaceNode(localDeclartionSyntax, ifClause);
return document.WithSyntaxRoot(editor.GetChangedRoot());
return document;
【问题讨论】:
【参考方案1】:早上我头脑清醒,我找到了解决办法。需要使用较旧的 SyntaxFactory 类(我之前发现但我查找了错误的关键字)
SingleVariableDesignationSyntax singleVariableDesignation = SyntaxFactory.SingleVariableDesignation(identifier);
DeclarationPatternSyntax singleVariableDeclaration = SyntaxFactory.DeclarationPattern(type, singleVariableDesignation);
IsPatternExpressionSyntax isPatternDeclaration = SyntaxFactory.IsPatternExpression(method, singleVariableDeclaration);
【讨论】:
以上是关于使用 Roslyn SyntaxGeneration 生成带有声明的模式匹配的主要内容,如果未能解决你的问题,请参考以下文章