コード例 #1
0
        public void AddCast(
            ISyntaxFacts syntaxFacts,
            SemanticModel semanticModel,
            SyntaxEditor editor,
            TForEachStatementSyntax forEachStatement,
            CancellationToken cancellationToken)
        {
            var expression         = syntaxFacts.GetExpressionOfForeachStatement(forEachStatement);
            var loopOperation      = (IForEachLoopOperation)semanticModel.GetRequiredOperation(forEachStatement, cancellationToken);
            var variableDeclarator = (IVariableDeclaratorOperation)loopOperation.LoopControlVariable;
            var enumerableType     = semanticModel.Compilation.GetBestTypeByMetadataName(typeof(Enumerable).FullName !);

            // These were already verified to be non-null in the analyzer.
            Contract.ThrowIfNull(variableDeclarator.Symbol.Type);
            Contract.ThrowIfNull(enumerableType);

            var elementType = GetForEachElementType(semanticModel, forEachStatement);
            var conversion  = semanticModel.Compilation.ClassifyCommonConversion(elementType, variableDeclarator.Symbol.Type);

            var rewritten = GetRewrittenCollection(editor.Generator, expression, variableDeclarator.Symbol.Type, conversion);

            // Add an annotation for System.Linq.Enumerable so that we add a `using System.Linq;` if not present.
            rewritten = rewritten.WithAdditionalAnnotations(
                Simplifier.Annotation, Simplifier.AddImportsAnnotation, SymbolAnnotation.Create(enumerableType));

            editor.ReplaceNode(expression, rewritten);
        }