當前位置: 首頁>>代碼示例>>C#>>正文


C# BinaryExpressionSyntax.AncestorsAndSelf方法代碼示例

本文整理匯總了C#中BinaryExpressionSyntax.AncestorsAndSelf方法的典型用法代碼示例。如果您正苦於以下問題:C# BinaryExpressionSyntax.AncestorsAndSelf方法的具體用法?C# BinaryExpressionSyntax.AncestorsAndSelf怎麽用?C# BinaryExpressionSyntax.AncestorsAndSelf使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在BinaryExpressionSyntax的用法示例。


在下文中一共展示了BinaryExpressionSyntax.AncestorsAndSelf方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: VisitBinaryExpression

            public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node)
            {
                var result = base.VisitBinaryExpression(node);
                var reducedNode = result as BinaryExpressionSyntax;
                if (reducedNode != node && reducedNode != null)
                {
                    if ((node.Left.IsKind(SyntaxKind.CastExpression) && !reducedNode.Left.IsKind(SyntaxKind.CastExpression)) ||
                        (node.Right.IsKind(SyntaxKind.CastExpression) && !reducedNode.Right.IsKind(SyntaxKind.CastExpression)))
                    {
                        // Cast simplification inside a binary expression, check if we need to parenthesize the binary expression to avoid breaking parent syntax.
                        // For example, cast removal in below case leads to syntax errors in error free code, unless parenting binary expression is parenthesized:
                        //   Original:                  Foo(x < (int)i, x > y)
                        //   Incorrect cast removal:    Foo(x < i, x > y)
                        //   Correct cast removal:      Foo((x < i), x > y)

                        // We'll do the following to detect such cases:
                        // 1) Get the topmostExpressionAncestor of node.
                        // 2) Get the reducedAncestor after replacing node with reducedNode within it.
                        // 3) Reparse the reducedAncestor to get reparsedAncestor.
                        // 4) Check for syntax equivalence of reducedAncestor and reparsedAncestor. If not syntactically equivalent,
                        //    then cast removal breaks the syntax and needs explicit parentheses around the binary expression.

                        var topmostExpressionAncestor = node
                            .AncestorsAndSelf()
                            .OfType<ExpressionSyntax>()
                            .LastOrDefault();

                        if (topmostExpressionAncestor != null && topmostExpressionAncestor != node)
                        {
                            var reducedAncestor = topmostExpressionAncestor.ReplaceNode(node, reducedNode);
                            var reparsedAncestor = SyntaxFactory.ParseExpression(reducedAncestor.ToFullString());
                            if (reparsedAncestor != null && !reparsedAncestor.IsEquivalentTo(reducedAncestor))
                            {
                                return SyntaxFactory.ParenthesizedExpression(reducedNode)
                                    .WithAdditionalAnnotations(Simplifier.Annotation);
                            }
                        }
                    }
                }

                return result;
            }
開發者ID:Rickinio,項目名稱:roslyn,代碼行數:42,代碼來源:CSharpCastReducer.Rewriter.cs

示例2: ScanIfElse

        internal static IEnumerable<CodeAction> ScanIfElse(SemanticModel ctx, Document document, SyntaxNode root, IfStatementSyntax ifElseStatement, BinaryExpressionSyntax isExpression, out int foundCastCount)
        {
            foundCastCount = 0;

            var innerCondition = ifElseStatement.Condition.SkipParens();
            if (innerCondition != null && innerCondition.IsKind(SyntaxKind.LogicalNotExpression))
            {
                var c2 = ((PrefixUnaryExpressionSyntax)innerCondition).Operand.SkipParens();
                if (c2.IsKind(SyntaxKind.IsExpression))
                {
                    return HandleNegatedCase(ctx, document, root, ifElseStatement, ifElseStatement.Condition, isExpression, out foundCastCount);
                }
                return Enumerable.Empty<CodeAction>();
            }

            var castToType = isExpression.Right;
            var embeddedStatment = ifElseStatement.Statement;

            var rr = ctx.GetTypeInfo(castToType);
            if (rr.Type == null || !rr.Type.IsReferenceType)
                return Enumerable.Empty<CodeAction>();
            List<SyntaxNode> foundCasts;
            foundCasts = embeddedStatment.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => IsCast(ctx, arg, rr.Type)).ToList();
            foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > isExpression.Span.End && IsCast(ctx, arg, rr.Type)));
            foundCastCount = foundCasts.Count;

            return new[] {
                CodeActionFactory.Create(
                    isExpression.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString ("Use 'as' and check for null"),
                    t2 => {
                        var varName = ReplaceAutoPropertyWithPropertyAndBackingFieldCodeRefactoringProvider.GetNameProposal(RefactoringHelpers.GuessNameFromType(rr.Type), ctx, isExpression);

                        var varDec = SyntaxFactory.LocalDeclarationStatement(
                            SyntaxFactory.VariableDeclaration(
                                SyntaxFactory.ParseTypeName("var"),
                                SyntaxFactory.SeparatedList(new [] {
                                    SyntaxFactory.VariableDeclarator(varName)
                                        .WithInitializer(SyntaxFactory.EqualsValueClause(
                                            SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, isExpression.Left, isExpression.Right)
                                        ))
                                })
                            ));
                        var outerIs = isExpression.AncestorsAndSelf().FirstOrDefault(e => !(e.Parent is ParenthesizedExpressionSyntax));
                        var binaryOperatorExpression = SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression, SyntaxFactory.IdentifierName(varName), SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
                        SyntaxNode newRoot;
                        if (IsEmbeddedStatement(ifElseStatement)) {
                            foundCasts = ifElseStatement.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => IsCast(ctx, arg, rr.Type)).ToList();
                            var newIf = ifElseStatement.TrackNodes(foundCasts.Concat(new [] { outerIs }));

                            newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(outerIs), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));

                            foreach (var c in foundCasts) {
                                newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                            }

                            var block = SyntaxFactory.Block(new StatementSyntax[] {
                                varDec,
                                newIf
                            });
                            newRoot = root.ReplaceNode((SyntaxNode)ifElseStatement, block.WithAdditionalAnnotations(Formatter.Annotation));
                        } else {
                            newRoot = root.TrackNodes(foundCasts.Concat(new SyntaxNode[] { ifElseStatement, outerIs }) );
                            newRoot = newRoot.InsertNodesBefore(newRoot.GetCurrentNode(ifElseStatement), new [] { varDec.WithAdditionalAnnotations(Formatter.Annotation) });
                            newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(outerIs), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));
                            foreach (var c in foundCasts) {
                                newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                            }
                        }

                        return Task.FromResult(document.WithSyntaxRoot(newRoot));
                    }
                )
            };
        }
開發者ID:Kavignon,項目名稱:RefactoringEssentials,代碼行數:76,代碼來源:UseAsAndNullCheckCodeRefactoringProvider.cs


注:本文中的BinaryExpressionSyntax.AncestorsAndSelf方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。