我正在为.Net开发Code Fix提供程序.
我想检查方法内部,例如来自IMethodSymbol的方法语句.
作为一个例子,我在输入上有以下代码:
public void DoSomething(string input)
{
if(input == null)
throw new InvalidOperationException("!!!!");
}
Run Code Online (Sandbox Code Playgroud)
在代码修复方面,我有IMethodSymbol接口,并且无法获取方法语句,内部节点等(我想看'if',条件为'if',异常提升等).
我怎么才能得到它?
我首先写了一个DiagnosticAnalyzer,然后努力让它加载,直到我在 VSIX 清单中将它的项目列为资产。
现在我还向CodeFixProvider与分析器相同的项目添加了一个,但它没有加载。
我错过了什么?
我尝试了以下方法:
类型构造函数以及实例构造函数和任何方法中的断点表明代码修复程序中没有任何内容被加载,也没有任何内容被命中。
这是代码修复程序的代码:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Capitec.CodeAnalysis.Diagnostics
{
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class UserInteractionCodeFixProvider : CodeFixProvider
{
private const string Title = "Invoke mapped function instead";
static UserInteractionCodeFixProvider()
{
}
public UserInteractionCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create( …Run Code Online (Sandbox Code Playgroud) 给定一个IMethodSymbol我如何创建一个MethodDeclarationSyntax?
背景:
对于代码修复,我将实现接口的一个类中的方法复制到实现不同接口的另一个类中。
因此,我需要修改复制方法的一些内容(参数、命名空间等)。我想修改IMethodSymbol,将符号转换为 a MethodDeclarationSyntax,然后将符号添加到新类中。
我已经能够通过使用来做到这一点DeclaringSyntaxReferences属性来做到这一点,但是当原始类驻留在 nuget 包中时,这不起作用。
使用DeclaringSyntaxReferences(以及我自己的一些代码)我能够执行以下操作:
public static MethodDeclarationSyntax[] ToMethodDeclarationSyntax(this IMethodSymbol methodSymbol)
{
var namespaceValue = methodSymbol.ContainingNamespace.GetNameSpaceIdentifier();
var syntaxReference = methodSymbol.DeclaringSyntaxReferences;
var syntaxNodes = syntaxReference.Select(syntaxRef => syntaxRef.GetSyntax());
var methodNodes = syntaxNodes.OfType<MethodDeclarationSyntax>();
var methodExpression = methodSymbol.CreateExpressionSyntax();
return methodNodes
.Select(mds => mds
.WithExpressionBody(methodExpression)
.WithReturnType(SyntaxFactory.QualifiedName(namespaceValue, SyntaxFactory.IdentifierName(mds.ReturnType.ToString())))
.WithParameterList(methodSymbol.GetFullyQualifiedParameterListSyntax())
)
.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法从 IMethodSymbol 生成 MethodDeclarationSyntax 而不使用DeclaringSyntaxReferences?
谢谢!