How do I replace a string variable with a var in Roslyn?

柔情痞子 提交于 2019-12-10 14:33:59

问题


For local declarations like: string a = string.Empty;

How can I write a diagnostic to change it to: var a = string.Empty;


回答1:


I've put together a code fix with diagnostic. Here's the interesting parts:

Implementation of AnalyzeNode from ISyntaxNodeAnalyzer

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
    {
        var localDeclaration = (LocalDeclarationStatementSyntax)node;
        if (localDeclaration.Declaration.Type.IsVar) return;
        var variable = localDeclaration.Declaration.Variables.First();
        var initialiser = variable.Initializer;
        if (initialiser == null) return;
        var variableTypeName = localDeclaration.Declaration.Type;
        var variableType = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;
        var initialiserInfo = semanticModel.GetTypeInfo(variable.Initializer.Value);
        var typeOfRightHandSideOfDeclaration = initialiserInfo.Type;
        if (Equals(variableType, typeOfRightHandSideOfDeclaration))
        {
            addDiagnostic(Diagnostic.Create(Rule, node.GetLocation(), localDeclaration.Declaration.Variables.First().Identifier.Value));
        }
    }

This essentially looks at the types on both sides of the declaration and if they're the same (and the RHS isn't already var) then add a diagnostic.

And here's the code for the Code Fix:

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
        var diagnosticSpan = diagnostics.First().Location.SourceSpan;
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
        return new[] { CodeAction.Create("Use var", c => ChangeDeclarationToVar(document, declaration, c)) };
    }

private async Task<Document> ChangeDeclarationToVar(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var variableTypeName = localDeclaration.Declaration.Type;
        var varTypeName = SyntaxFactory.IdentifierName("var").WithAdditionalAnnotations(Formatter.Annotation);
        var newDeclaration = localDeclaration.ReplaceNode(variableTypeName, varTypeName);            
        var newRoot = root.ReplaceNode(localDeclaration, newDeclaration);
        return document.WithSyntaxRoot(newRoot);
    }

This bit is nice and simple, just get var from the Syntax factory and switch it out. Note that var doesn't have it's own static method in the SyntaxFactory so instead is reference by name.




回答2:


You can't. The var keyword tells the compiler to perform type inference, and with just var a; the compiler doesn't have enough information to infer a type.

You could however do any of the following

var a = new String();
var b = String.Empty;
var c = "";

but this seems like more effort than it's worth.

Edit for updated request: Why do you want to modify all the code to be declared with var? It compiles to the same IL anyway (trivially simple example):

// var a = String.Empty;
IL_0000:  ldsfld     string [mscorlib]System.String::Empty
IL_0005:  pop
// string b = String.Empty;
IL_0006:  ldsfld     string [mscorlib]System.String::Empty
IL_000b:  pop



回答3:


The compiler can't infer the type from that.

You would need to use:

var a = ""; // compiler can see that is type `string`:

or you can do:

string a;


来源:https://stackoverflow.com/questions/23227644/how-do-i-replace-a-string-variable-with-a-var-in-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!