public static async Task <Solution> DeclareLocalVariable(CodeRefactoringContext context, String typeName)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var currentNode               = root.FindNode(context.Span);
            var statement                 = currentNode.AncestorsAndSelf().OfType <ExpressionStatementSyntax>().FirstOrDefault();
            var invocationExpression      = statement.DescendantNodesAndSelf().OfType <InvocationExpressionSyntax>().First();
            var identifierName            = invocationExpression.DescendantNodesAndSelf().LastOrDefault(n => n is IdentifierNameSyntax) as IdentifierNameSyntax;
            var methodName                = LocalNameByMathodNameGenerator.CreateIdentifierName(identifierName.Identifier.ValueText);
            var localVariableName         = LocalVariableNameGenerator.Create(methodName, currentNode, await context.Document.GetSemanticModelAsync());
            var localDeclarationStatement = LocalDeclarationStatementFactory.Create(typeName, localVariableName, invocationExpression);

            return(await SolutionNodeReplacer.Replace(context, localDeclarationStatement, statement));
        }
예제 #2
0
        public static async Task <Solution> CreateDefaultObject(CodeRefactoringContext context, Boolean leftTypeNameIsVar)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var currentNode   = root.FindNode(context.Span);
            var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken);

            var statement = currentNode.AncestorsAndSelf().First(n => n is ExpressionStatementSyntax ||
                                                                 n is LocalDeclarationStatementSyntax) as StatementSyntax;
            var type = GetTypeInfo(statement, semanticModel);
            var localVariableName         = LocalVariableNameGenerator.Create(GetNameForLocalVariable(type), currentNode, semanticModel);
            var typeName                  = statement.WithoutTrivia().GetText().ToString().Replace(" ", "").TrimEnd(';');
            var leftTypeName              = leftTypeNameIsVar ? "var" : typeName;
            var localDeclarationStatement = LocalDeclarationStatementFactory.CreateLocalObjectStatement(leftTypeName, typeName, localVariableName);

            return(await SolutionNodeReplacer.Replace(context, localDeclarationStatement, statement));
        }