当前位置: 首页>>代码示例>>C#>>正文


C# Diagnostic类代码示例

本文整理汇总了C#中Diagnostic的典型用法代码示例。如果您正苦于以下问题:C# Diagnostic类的具体用法?C# Diagnostic怎么用?C# Diagnostic使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Diagnostic类属于命名空间,在下文中一共展示了Diagnostic类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken token = root.FindToken(diagnostic.Location.SourceSpan.Start);
            if (!token.IsKind(SyntaxKind.CloseBracketToken))
            {
                return document;
            }

            if (token.IsFirstInLine())
            {
                return document;
            }

            SyntaxToken precedingToken = token.GetPreviousToken();
            if (!precedingToken.TrailingTrivia.Any(SyntaxKind.WhitespaceTrivia))
            {
                return document;
            }

            SyntaxToken corrected = precedingToken.WithoutTrailingWhitespace().WithoutFormatting();
            SyntaxNode transformed = root.ReplaceToken(precedingToken, corrected);
            Document updatedDocument = document.WithSyntaxRoot(transformed);

            return updatedDocument;
        }
开发者ID:hickford,项目名称:StyleCopAnalyzers,代码行数:27,代码来源:SA1017CodeFixProvider.cs

示例2: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var anyInvoke = nodeContext.Node as InvocationExpressionSyntax;

            var info = nodeContext.SemanticModel.GetSymbolInfo(anyInvoke);

            IMethodSymbol anyResolve = info.Symbol as IMethodSymbol;
            if (anyResolve == null)
            {
                anyResolve = info.CandidateSymbols.OfType<IMethodSymbol>().FirstOrDefault(candidate => HasPredicateVersion(candidate));
            }

            if (anyResolve == null || !HasPredicateVersion(anyResolve))
                return false;

            ExpressionSyntax target, followUp;
            TypeSyntax type;
            ParameterSyntax param;
            if (ReplaceWithOfTypeAnyAnalyzer.MatchSelect(anyInvoke, out target, out type, out param, out followUp))
            {
                // if (member == "Where" && followUp == null) return;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    anyInvoke.GetLocation()
                );
                return true;
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:30,代码来源:ReplaceWithOfTypeFirstAnalyzer.cs

示例3: TryGetDiagnostic

        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            var localDeclarationUnused = nodeContext.Node as LocalDeclarationStatementSyntax;
            var body = localDeclarationUnused?.Parent as BlockSyntax;
            if (body == null)
                return false;

            var dataFlow = nodeContext.SemanticModel.AnalyzeDataFlow(body);
            var variablesDeclared = dataFlow.VariablesDeclared;
            var variablesRead = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
            var unused = variablesDeclared.Except(variablesRead).ToArray();
            if (unused == null)
                return false;

            if (localDeclarationUnused.Declaration == null || !localDeclarationUnused.Declaration.Variables.Any())
                return false; 

            var localDeclarationSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(localDeclarationUnused.Declaration.Variables.FirstOrDefault());
            if (unused.Any())
            {
                if (unused.Contains(localDeclarationSymbol))
                {
                    diagnostic = Diagnostic.Create(descriptor, localDeclarationUnused.Declaration.GetLocation());
                    return true;
                }
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:30,代码来源:LocalVariableNotUsedAnalyzer.cs

示例4: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as MethodDeclarationSyntax;

            if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.OverrideKeyword)))
                return false;
            var lastParam = node.ParameterList.Parameters.LastOrDefault();
            if (lastParam == null || lastParam.Modifiers.Any(m => m.IsKind(SyntaxKind.ParamsKeyword)))
                return false;
            if (lastParam.Type == null || !lastParam.Type.IsKind(SyntaxKind.ArrayType))
                return false;
            var rr = nodeContext.SemanticModel.GetDeclaredSymbol(node);
            if (rr == null || !rr.IsOverride)
                return false;
            var baseMember = rr.OverriddenMethod;
            if (baseMember == null || baseMember.Parameters.Length == 0 || !baseMember.Parameters.Last().IsParams)
                return false;

            diagnostic = Diagnostic.Create(
                descriptor,
                lastParam.GetLocation(),
                baseMember.Name
            );
            return true;
        }
开发者ID:pgrefviau,项目名称:RefactoringEssentials,代码行数:28,代码来源:BaseMemberHasParamsAnalyzer.cs

示例5: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var node = nodeContext.Node as InvocationExpressionSyntax;
            MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax;
            if (mre == null)
                return false;
            if (mre.Name.Identifier.ValueText != "StartsWith")
                return false;

            var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken);
            if (rr.Symbol == null)
                return false;
            var symbol = rr.Symbol;
            if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String))
                return false;
            var parameters = symbol.GetParameters();
            var firstParameter = parameters.FirstOrDefault();
            if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String)
                return false;   // First parameter not a string
            var lastParameter = parameters.Last();
            if (lastParameter.Type.Name == "StringComparison")
                return false;   // already specifying a string comparison
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:29,代码来源:StringStartsWithIsCultureSpecificAnalyzer.cs

示例6: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            InitializerExpressionSyntax initializer = null;
            var node = nodeContext.Node as ArrayCreationExpressionSyntax;
            if (node != null) initializer = node.Initializer;
            var inode = nodeContext.Node as ImplicitArrayCreationExpressionSyntax;
            if (inode != null) initializer = inode.Initializer;

            if (initializer == null)
                return false;
            var varInitializer = nodeContext.Node.Parent.Parent;
            if (varInitializer == null)
                return false;
            var variableDeclaration = varInitializer.Parent as VariableDeclarationSyntax;
            if (variableDeclaration != null)
            {
                if (!variableDeclaration.Type.IsKind(SyntaxKind.ArrayType))
                    return false;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    Location.Create(nodeContext.SemanticModel.SyntaxTree, TextSpan.FromBounds((node != null ? node.NewKeyword : inode.NewKeyword).Span.Start, initializer.Span.Start))
                );
                return true;
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:28,代码来源:ArrayCreationCanBeReplacedWithArrayInitializerAnalyzer.cs

示例7: GetTransformedDocumentAsync

        private async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
        {
            var syntaxRoot = await document.GetSyntaxRootAsync(token).ConfigureAwait(false);
            var newDocument = this.CreateCodeFix(document, diagnostic, syntaxRoot);

            return newDocument;
        }
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:7,代码来源:SA1502CodeFixProvider.cs

示例8: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var node = nodeContext.Node as AssignmentExpressionSyntax;

            if (node.IsKind(SyntaxKind.OrAssignmentExpression))
            {
                LiteralExpressionSyntax right = node.Right as LiteralExpressionSyntax;
                //if right is true
                if ((right != null) && right.IsKind(SyntaxKind.TrueLiteralExpression))
                {
                    diagnostic = Diagnostic.Create(
                        descriptor,
                        node.GetLocation()
                    );
                    return true;
                }

            }
            else if (node.IsKind(SyntaxKind.AndAssignmentExpression))
            {
                LiteralExpressionSyntax right = node.Right as LiteralExpressionSyntax;
                //if right is false
                if ((right != null) && right.IsKind(SyntaxKind.FalseLiteralExpression))
                {
                    diagnostic = Diagnostic.Create(
                        descriptor,
                        node.GetLocation()
                    );
                    return true;
                }
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:34,代码来源:ReplaceWithSimpleAssignmentAnalyzer.cs

示例9: GetTransformedDocumentAsync

        private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken token)
        {
            var sourceText = await document.GetTextAsync(token).ConfigureAwait(false);

            var startIndex = sourceText.Lines.IndexOf(diagnostic.Location.SourceSpan.Start);
            int endIndex = startIndex;

            for (var i = startIndex + 1; i < sourceText.Lines.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(sourceText.Lines[i].ToString()))
                {
                    endIndex = i - 1;
                    break;
                }
            }

            if (endIndex >= (startIndex + 1))
            {
                var replaceSpan = TextSpan.FromBounds(sourceText.Lines[startIndex + 1].SpanIncludingLineBreak.Start, sourceText.Lines[endIndex].SpanIncludingLineBreak.End);
                var newSourceText = sourceText.Replace(replaceSpan, string.Empty);
                return document.WithText(newSourceText);
            }

            return document;
        }
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:25,代码来源:SA1507CodeFixProvider.cs

示例10: RegisterMethodDocumentationCodeFix

 /// <summary>
 /// Register the property fix for property documentation.
 /// </summary>
 /// <param name="root">the syntax root node.</param>
 /// <param name="context">the code fix context, containing the location of the fix.</param>
 /// <param name="diagnostic">the diagnostic, where the invalid code was located.</param>
 private void RegisterMethodDocumentationCodeFix(SyntaxNode root, CodeFixContext context, Diagnostic diagnostic)
 {
     var startNode = root.FindNode(diagnostic.Location.SourceSpan);
     var constructorDeclaration = startNode as ConstructorDeclarationSyntax;
     if (constructorDeclaration != null)
         this.RegisterConstructorCodeFix(constructorDeclaration, root, context, diagnostic);
 }
开发者ID:jimmymain,项目名称:Documentation.Analyzers,代码行数:13,代码来源:DocumentationConstructorCodeFixProvider.cs

示例11: GetNewStartToken

            private static SyntaxToken GetNewStartToken(SyntaxToken startToken, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer)
            {
                var trivia = startToken.LeadingTrivia.ToImmutableArray();

                // Insert the #pragma disable directive after all leading new line trivia but before first trivia of any other kind.
                int index;
                SyntaxTrivia firstNonEOLTrivia = trivia.FirstOrDefault(t => !fixer.IsEndOfLine(t));
                if (firstNonEOLTrivia == default(SyntaxTrivia))
                {
                    index = trivia.Length;
                }
                else
                {
                    index = trivia.IndexOf(firstNonEOLTrivia);
                }

                bool needsLeadingEOL;
                if (index > 0)
                {
                    needsLeadingEOL = !fixer.IsEndOfLine(trivia[index - 1]);
                }
                else if (startToken.FullSpan.Start == 0)
                {
                    needsLeadingEOL = false;
                }
                else
                {
                    needsLeadingEOL = true;
                }

                var pragmaWarningTrivia = fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, needsLeadingEOL);

                return startToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaWarningTrivia));
            }
开发者ID:noahfalk,项目名称:roslyn,代码行数:34,代码来源:AbstractSuppressionCodeFixProvider.PragmaWarningCodeAction.cs

示例12: GetMessagePrefix

        internal string GetMessagePrefix(Diagnostic diagnostic, CultureInfo culture)
        {
            string prefix;
            switch (diagnostic.Severity)
            {
                case DiagnosticSeverity.Hidden:
                    prefix = CodeAnalysisResources.ResourceManager.GetString(nameof(CodeAnalysisResources.SeverityHidden), culture);
                    break;
                case DiagnosticSeverity.Info:
                    prefix = CodeAnalysisResources.ResourceManager.GetString(nameof(CodeAnalysisResources.SeverityInfo), culture);
                    break;
                case DiagnosticSeverity.Warning:
                    prefix = CodeAnalysisResources.ResourceManager.GetString(nameof(CodeAnalysisResources.SeverityWarning), culture);
                    break;
                case DiagnosticSeverity.Error:
                    prefix = CodeAnalysisResources.ResourceManager.GetString(nameof(CodeAnalysisResources.SeverityError), culture);
                    break;
                default:
                    throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity);
            }

            return string.Format(culture, "{0} {1}",
                prefix,
                diagnostic.Id);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:25,代码来源:DiagnosticFormatter.cs

示例13: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            var options = nodeContext.SemanticModel.SyntaxTree.Options as VisualBasicParseOptions;
            if (options != null && options.LanguageVersion < LanguageVersion.VisualBasic14)
                return false;

            var objectCreateExpression = nodeContext.Node as ObjectCreationExpressionSyntax;

            ExpressionSyntax paramNode;
            if (!CheckExceptionType(nodeContext.SemanticModel, objectCreateExpression, out paramNode))
                return false;
            var paramName = GetArgumentParameterName(paramNode);
            if (paramName == null)
                return false;

            var validNames = GetValidParameterNames(objectCreateExpression);

            if (!validNames.Contains(paramName))
                return false;

            diagnostic = Diagnostic.Create(descriptor, paramNode.GetLocation(), paramName);
            return true;
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:25,代码来源:NameOfSuggestionAnalyzer.cs

示例14: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            var node = nodeContext.Node as BinaryExpressionSyntax;

            var flowAnalzyer = new FlowAnalyzer<NullFlowState>(nodeContext.SemanticModel, new NullFlowState(nodeContext.SemanticModel));

            var analyzer = flowAnalzyer.Analyze(nodeContext.Node);
            var state = analyzer.GetFlowState(node.Left);

            var leftState = state.GetReferenceState(node.Left);
            if (leftState == NullState.NotNull) {
                diagnostic = Diagnostic.Create (descriptor, node.Right.GetLocation (), "Remove redundant right side");
                return true;
            }
            if (leftState == NullState.Null) {
                diagnostic = Diagnostic.Create (descriptor, node.Left.GetLocation (), "Remove redundant left side");
                return true;
            }
            if (state.GetReferenceState(node.Right) == NullState.Null) {
                diagnostic = Diagnostic.Create (descriptor, node.Right.GetLocation (), "Remove redundant left side");
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:25,代码来源:ConstantNullCoalescingConditionAnalyzer.cs

示例15: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var node = nodeContext.Node as LocalDeclarationStatementSyntax;
            var member = node.AncestorsAndSelf().FirstOrDefault(n => n is MemberDeclarationSyntax);
            if (member == null)
                return false;
            var symbols = nodeContext.SemanticModel.LookupSymbols(member.SpanStart);
            var memberSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(member);

            foreach (var variable in node.Declaration.Variables)
            {
                var hidingMember = symbols.FirstOrDefault(v => v.Name == variable.Identifier.ValueText && ((memberSymbol.IsStatic && v.IsStatic) || !memberSymbol.IsStatic) && !v.IsKind(SymbolKind.Local) && !v.IsKind(SymbolKind.Parameter));
                if (hidingMember == null)
                    continue;

                var mre = variable.Initializer?.Value as MemberAccessExpressionSyntax;
                if (mre != null && mre.Name.Identifier.ValueText == hidingMember.Name && mre.Expression.IsKind(SyntaxKind.ThisExpression))
                {
                    // Special case: the variable is initialized from the member it is hiding
                    // In this case, the hiding is obviously intentional and we shouldn't show a warning.
                    continue;
                }
                string memberType = GetMemberType(hidingMember.Kind);
                diagnostic = Diagnostic.Create(descriptor, variable.Identifier.GetLocation(), variable.Identifier, memberType, hidingMember.Name);
                return true;
            }
            return false;
        }
开发者ID:petterek,项目名称:RefactoringEssentials,代码行数:29,代码来源:LocalVariableHidesMemberAnalyzer.cs


注:本文中的Diagnostic类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。