• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# CodeFixes.CodeFixContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: RegisterCodeFixesAsync

		public async override Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			var document = context.Document;
			var cancellationToken = context.CancellationToken;
			var diagnostics = context.Diagnostics;
			var root = await document.GetSyntaxRootAsync(cancellationToken);
			var diagnostic = diagnostics.First();
			var node = root.FindNode(context.Span) as BinaryExpressionSyntax;
			if (node == null)
				return;
			StatementSyntax expression = null;
			var ifStatement = node.Parent as IfStatementSyntax;
			if (ifStatement == null)
				return;
            var statement = ifStatement.Statement;
			if (statement is BlockSyntax)
				expression = ((BlockSyntax)statement).Statements[0];
			else
				expression = statement;

			if (expression == null)
				return;

			context.RegisterCodeFix(CodeAction.Create("Remove redundant check", async token => {
				var editor = await DocumentEditor.CreateAsync(document, cancellationToken);
				expression = expression
					.WithOrderedTriviaFromSubTree(ifStatement)
					.WithAdditionalAnnotations(Formatter.Annotation);
                editor.ReplaceNode(ifStatement, expression);
				return editor.GetChangedDocument();
			}, string.Empty), diagnostic);
		}
开发者ID:nhabuiduc,项目名称:RefactoringEssentials,代码行数:32,代码来源:RedundantCheckBeforeAssignmentCodeFixProvider.cs


示例2: RegisterCodeFixesAsync

        /// <inheritdoc/>
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var root = await document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            foreach (var diagnostic in context.Diagnostics)
            {
                if (!diagnostic.Id.Equals(SA1309FieldNamesMustNotBeginWithUnderscore.DiagnosticId))
                {
                    continue;
                }

                var token = root.FindToken(diagnostic.Location.SourceSpan.Start);
                if (token.IsMissing)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(token.ValueText))
                {
                    var newName = token.ValueText.TrimStart(new[] { '_' });

                    if (string.IsNullOrEmpty(newName))
                    {
                        // The variable consisted of only underscores. In this case we cannot
                        // generate a valid variable name and thus will not offer a code fix.
                        continue;
                    }

                    context.RegisterCodeFix(CodeAction.Create(string.Format(NamingResources.SA1309CodeFix, newName), cancellationToken => RenameHelper.RenameSymbolAsync(document, root, token, newName, cancellationToken), equivalenceKey: nameof(SA1309CodeFixProvider)), diagnostic);
                }
            }
        }
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:34,代码来源:SA1309CodeFixProvider.cs


示例3: VerifyGetFixesWhenUsingSystemDoesNotExist

    public async Task VerifyGetFixesWhenUsingSystemDoesNotExist()
    {
      var code = File.ReadAllText(
        [email protected]"Targets\{nameof(IsBusinessObjectSerializableMakeSerializableCodeFixTests)}.{(nameof(this.VerifyGetFixesWhenUsingSystemDoesNotExist))}.cs");
      var document = TestHelpers.Create(code);
      var tree = await document.GetSyntaxTreeAsync();
      var diagnostics = await TestHelpers.GetDiagnosticsAsync(code, new IsBusinessObjectSerializableAnalyzer());
      var sourceSpan = diagnostics[0].Location.SourceSpan;

      var actions = new List<CodeAction>();
      var codeActionRegistration = new Action<CodeAction, ImmutableArray<Diagnostic>>(
        (a, _) => { actions.Add(a); });

      var fix = new IsBusinessObjectSerializableMakeSerializableCodeFix();
      var codeFixContext = new CodeFixContext(document, diagnostics[0],
        codeActionRegistration, new CancellationToken(false));
      await fix.RegisterCodeFixesAsync(codeFixContext);

      Assert.AreEqual(2, actions.Count, nameof(actions.Count));

      await TestHelpers.VerifyActionAsync(actions,
        IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSystemSerializableDescription, document,
        tree, $"{Environment.NewLine}[System.Serializable]");
      await TestHelpers.VerifyActionAsync(actions,
        IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription, document,
        tree, $"using System;{Environment.NewLine}{Environment.NewLine}[Serializable]");
    }
开发者ID:rachmann,项目名称:csla,代码行数:27,代码来源:IsBusinessObjectSerializableMakeSerializableCodeFixTests.cs


示例4: RegisterCodeFixesAsync

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            if (model.IsFromGeneratedCode(cancellationToken))
                return;
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            var diagnostic = diagnostics.First();
            var node = root.FindNode(context.Span);
            context.RegisterCodeFix(CodeActionFactory.Create(
                node.Span,
                diagnostic.Severity,
                GettextCatalog.GetString("Add 'new' modifier"),
                token =>
                {
                    SyntaxNode newRoot;
                    if (node.Kind() != SyntaxKind.VariableDeclarator)
                        newRoot = root.ReplaceNode(node, AddNewModifier(node));
                    else //this one wants to be awkward - you can't add modifiers to a variable declarator
                    {
                        SyntaxNode declaringNode = node.Parent.Parent;
                        if (declaringNode is FieldDeclarationSyntax)
                            newRoot = root.ReplaceNode(node.Parent.Parent, (node.Parent.Parent as FieldDeclarationSyntax).AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)));
                        else //it's an event declaration
                            newRoot = root.ReplaceNode(node.Parent.Parent, (node.Parent.Parent as EventFieldDeclarationSyntax).AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)));
                    }
                    return Task.FromResult(document.WithSyntaxRoot(newRoot.WithAdditionalAnnotations(Formatter.Annotation)));
                }), diagnostic);
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:33,代码来源:CS0108UseNewKeywordIfHidingIntendedCodeFixProvider.cs


示例5: GetFixes

		public async Task GetFixes()
		{
			var code =
@"using System.ServiceModel;

public class AClass
{
	[OperationContract(IsOneWay = true)]
	public string AMethod() { return string.Empty; }
}";

			var document = TestHelpers.Create(code);
			var tree = await document.GetSyntaxTreeAsync();
			var diagnostics = await TestHelpers.GetDiagnosticsAsync(
				code, new IsOneWayOperationAnalyzer());
			var sourceSpan = diagnostics[0].Location.SourceSpan;

			var actions = new List<CodeAction>();
			var codeActionRegistration = new Action<CodeAction, ImmutableArray<Diagnostic>>(
			  (a, _) => { actions.Add(a); });

			var fix = new IsOneWayOperationMakeIsOneWayFalseCodeFix();
			var codeFixContext = new CodeFixContext(document, diagnostics[0],
			  codeActionRegistration, new CancellationToken(false));
			await fix.RegisterCodeFixesAsync(codeFixContext);

			Assert.Equal(1, actions.Count);

			await TestHelpers.VerifyActionAsync(actions,
			  IsOneWayOperationMakeIsOneWayFalseCodeFixConstants.Description, document,
			  tree, new[] { "fals" });
		}
开发者ID:JasonBock,项目名称:FixingIsOneWay,代码行数:32,代码来源:IsOneWayOperationMakeIsOneWayFalseCodeFixTests.cs


示例6: RegisterCodeFixesAsync

        /// <inheritdoc/>
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            foreach (var diagnostic in context.Diagnostics)
            {
                SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
                if (node == null || node.IsMissing)
                {
                    continue;
                }

                SyntaxNode declarationNode = FindParentDeclarationNode(node);
                if (declarationNode == null)
                {
                    continue;
                }

                context.RegisterCodeFix(
                    CodeAction.Create(
                        MaintainabilityResources.SA1400CodeFix,
                        cancellationToken => GetTransformedDocumentAsync(context.Document, root, declarationNode),
                        nameof(SA1400CodeFixProvider)),
                    diagnostic);
            }
        }
开发者ID:Romanx,项目名称:StyleCopAnalyzers,代码行数:26,代码来源:SA1400CodeFixProvider.cs


示例7: RegisterCodeFixesAsync

        /// <inheritdoc/>
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                var documentRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
                SyntaxNode syntax = documentRoot.FindNode(diagnostic.Location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
                if (syntax == null)
                {
                    continue;
                }

                XmlElementSyntax xmlElementSyntax = syntax as XmlElementSyntax;
                if (xmlElementSyntax == null)
                {
                    // We continue even for placeholders if they are empty elements (XmlEmptyElementSyntax)
                    continue;
                }

                if (string.IsNullOrWhiteSpace(xmlElementSyntax.Content.ToString()))
                {
                    // The placeholder hasn't been updated yet.
                    continue;
                }

                context.RegisterCodeFix(
                    CodeAction.Create(
                        DocumentationResources.SA1651CodeFix,
                        cancellationToken => this.GetTransformedDocumentAsync(context.Document, xmlElementSyntax, cancellationToken),
                        nameof(SA1651CodeFixProvider)),
                    diagnostic);
            }
        }
开发者ID:JaRau,项目名称:StyleCopAnalyzers,代码行数:33,代码来源:SA1651CodeFixProvider.cs


示例8: RegisterCodeFixesAsync

 public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
 {
     var diagnostic = context.Diagnostics.First();
     context.RegisterCodeFix(CodeAction.Create(
         "Removes redundant comparision", c => RemoveRedundantComparisonAsync(context.Document, diagnostic, c), nameof(SimplifyRedundantBooleanComparisonsCodeFixProvider)), diagnostic);
     return Task.FromResult(0);
 }
开发者ID:Cadums01,项目名称:code-cracker,代码行数:7,代码来源:SimplifyRedundantBooleanComparisonsCodeFixProvider.cs


示例9: RegisterCodeFixesAsync

        public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var syntaxNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true);

            var statement = syntaxNode as StatementSyntax;
            var assignment = syntaxNode as AssignmentExpressionSyntax;
            var binary = syntaxNode as BinaryExpressionSyntax;
            if (statement != null ||
                assignment != null ||
                binary != null)
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        Title,
                        c =>
                        {
                            var newRoot = CalculateNewRoot(root, diagnostic, statement, assignment, binary);
                            return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                        }),
                    context.Diagnostics);
            }
        }
开发者ID:ozgurkayaist,项目名称:sonarlint-vs,代码行数:26,代码来源:SillyBitwiseOperationCodeFixProvider.cs


示例10: RegisterCodeFixesAsync

 public override sealed Task RegisterCodeFixesAsync(CodeFixContext context)
 {
     var diagnostic = context.Diagnostics.First();
     if (diagnostic.Properties["kind"] == "missingDoc")
         context.RegisterCodeFix(CodeAction.Create(Resources.XmlDocumentationCreateMissingParametersCodeFixProvider_Title, c => FixParametersAsync(context.Document, diagnostic, c)), diagnostic);
     return Task.FromResult(0);
 }
开发者ID:gerryaobrien,项目名称:code-cracker,代码行数:7,代码来源:XmlDocumentationCreateMissingParametersCodeFixProvider.cs


示例11: RegisterCodeFixesAsync

        public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var initializer = root.FindNode(diagnosticSpan) as ConstructorInitializerSyntax;
            if (initializer == null)
            {
                return;
            }

            var constructor = initializer.Parent as ConstructorDeclarationSyntax;
            if (constructor == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        var newRoot = RemoveInitializer(root, constructor);
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
开发者ID:jakobehn,项目名称:sonarlint-vs,代码行数:27,代码来源:DefaultBaseConstructorCallCodeFixProvider.cs


示例12: AddFix

 private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
 {
     var fix = new MyCodeAction(
         codeFixTitle,
         c => GetFix(context.Document, root, classDecl, generator, languages));
     context.RegisterCodeFix(fix, context.Diagnostics);
 }
开发者ID:GloryChou,项目名称:roslyn,代码行数:7,代码来源:ApplyDiagnosticAnalyzerAttributeFix.cs


示例13: RegisterCodeFixesAsync

        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var token = root.FindToken(context.Span.Start);
            if (!token.Span.IntersectsWith(context.Span))
            {
                return;
            }

            var generator = SyntaxGenerator.GetGenerator(context.Document);
            var classDecl = generator.GetDeclaration(token.Parent);
            if (classDecl == null)
            {
                return;
            }

            // Register fixes.

            // 1) Apply C# DiagnosticAnalyzerAttribute.
            var title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp);
            AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp);

            // 2) Apply VB DiagnosticAnalyzerAttribute.
            title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.VisualBasic);
            AddFix(title, context, root, classDecl, generator, LanguageNames.VisualBasic);

            // 3) Apply both C# and VB DiagnosticAnalyzerAttributes.
            title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_2, LanguageNames.CSharp, LanguageNames.VisualBasic);
            AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp, LanguageNames.VisualBasic);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:30,代码来源:ApplyDiagnosticAnalyzerAttributeFix.cs


示例14: RegisterCodeFixesAsync

        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var syntaxFactoryService = SyntaxGenerator.GetGenerator(context.Document);
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var node = root.FindNode(context.Span);

            // We cannot have multiple overlapping diagnostics of this id.
            var diagnostic = context.Diagnostics.Single();

            if (IsInArgumentContext(node))
            {
                // StringComparison.CurrentCulture => StringComparison.Ordinal
                // StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
                context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
                                                         async ct => await FixArgument(context.Document, syntaxFactoryService, root, node).ConfigureAwait(false)),
                                                    diagnostic);
            }
            else if (IsInIdentifierNameContext(node))
            {
                // string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
                // string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
                context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
                                                         async ct => await FixIdentifierName(context.Document, syntaxFactoryService, root, node, context.CancellationToken).ConfigureAwait(false)),
                                                    diagnostic);
            }
            else if (IsInEqualsContext(node))
            {
                // "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
                // "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
                context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.UseOrdinalStringComparisonTitle,
                                async ct => await FixEquals(context.Document, syntaxFactoryService, root, node, context.CancellationToken).ConfigureAwait(false)),
                        diagnostic);
            }
        }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:34,代码来源:UseOrdinalStringComparison.Fixer.cs


示例15: RegisterCodeFixesAsync

        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            var declaration = root.FindNode(context.Span);
            if (declaration == null)
            {
                return;
            }

            // find a Dispose method
            var iDisposableType = model.Compilation.GetSpecialType(SpecialType.System_IDisposable);
            var iDisposable_Dispose = (iDisposableType?.GetMembers(DisposableFieldsShouldBeDisposedAnalyzer.Dispose))?.Single();
            if (iDisposableType == null || iDisposable_Dispose == null)
            {
                return;
            }

            var fieldSymbol = model.GetDeclaredSymbol(declaration, context.CancellationToken) as IFieldSymbol;
            var disposeMethod = fieldSymbol?.ContainingType?.FindImplementationForInterfaceMember(iDisposable_Dispose) as IMethodSymbol;
            if (disposeMethod == null)
            {
                return;
            }

            // We cannot have multiple overlapping diagnostics of this id.
            var diagnostic = context.Diagnostics.Single();

            context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.DisposableFieldsShouldBeDisposedMessage,
                                                     async ct => await AddDisposeCall(context.Document, declaration, fieldSymbol, disposeMethod, iDisposableType, iDisposable_Dispose, ct).ConfigureAwait(false)),
                                    diagnostic);
        }
开发者ID:ondrejsevcik,项目名称:roslyn-analyzers,代码行数:34,代码来源:DisposableFieldsShouldBeDisposed.Fixer.cs


示例16: AddCodeFix

    private static void AddCodeFix(CodeFixContext context, SyntaxNode root,
      Diagnostic diagnostic, ClassDeclarationSyntax classNode)
    {
      var newRoot = IsBusinessObjectSerializableMakeSerializableCodeFix.AddAttribute(
        root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName);

      if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace))
      {
        newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
          SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
            IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace)));
      }

      if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace))
      {
        newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
          SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
            IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace)));
      }

      context.RegisterCodeFix(
        CodeAction.Create(
          IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription,
          _ => Task.FromResult<Document>(context.Document.WithSyntaxRoot(newRoot))), diagnostic);
    }
开发者ID:pombredanne,项目名称:csla,代码行数:25,代码来源:IsBusinessObjectSerializableMakeSerializableCodeFix.cs


示例17: RegisterCodeFixesAsync

        public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            //  var syntaxNode = root.FindNode(diagnosticSpan);
            //var declaration = root.FindToken(diagnosticSpan.Start);
            // var firstToken = declaration.GetFirstToken();
            // var leadingTrivia = firstToken.LeadingTrivia;
            // var trimmedLocal = declaration.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
            var cw = new AdhocWorkspace();
            OptionSet options = cw.Options;
            options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInMethods, false);
            options = options.WithChangedOption(CSharpFormattingOptions.IndentBlock, false);
            context.RegisterCodeFix(
     CodeAction.Create(
         Title,
        async c =>
         {
             var oldNode = root.FindTrivia(diagnosticSpan.Start);
             var newRoot = root.ReplaceTrivia(oldNode, SyntaxTriviaList.Empty);
             newRoot = newRoot.WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = Formatter.Format(newRoot, new AdhocWorkspace(),options);
             //TODO:Need to remove empty line if it followed by a comment(Formatting).
             return await Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
         }),
     context.Diagnostics);
        }
开发者ID:Thejas007,项目名称:sonarlint-vs,代码行数:29,代码来源:CommentedOutCodeCodeFixProvider.cs


示例18: RegisterCodeFixesAsync

    public override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
      var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

      if (context.CancellationToken.IsCancellationRequested)
      {
        return;
      }

      var diagnostic = context.Diagnostics.First();
      var classNode = root.FindNode(diagnostic.Location.SourceSpan) as ClassDeclarationSyntax;

      if (context.CancellationToken.IsCancellationRequested)
      {
        return;
      }

      var hasNonPublicNoArgumentConstructor = bool.Parse(diagnostic.Properties[PublicNoArgumentConstructorIsMissingConstants.HasNonPublicNoArgumentConstructor]);

      if(hasNonPublicNoArgumentConstructor)
      {
        CheckConstructorsAnalyzerPublicConstructorCodeFix.AddCodeFixWithUpdatingNonPublicConstructor(
          context, root, diagnostic, classNode);
      }
      else
      {
        CheckConstructorsAnalyzerPublicConstructorCodeFix.AddCodeFixWithNewPublicConstructor(
          context, root, diagnostic, classNode);
      }
    }
开发者ID:JorgeArellano,项目名称:csla,代码行数:30,代码来源:CheckConstructorsAnalyzerPublicConstructorCodeFix.cs


示例19: RegisterCodeFixesAsync

        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var generator = SyntaxGenerator.GetGenerator(context.Document);
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var declaration = root.FindNode(context.Span);
            declaration = generator.GetDeclaration(declaration);
            if (declaration == null)
            {
                return;
            }

            var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
            var typeSymbol = model.GetDeclaredSymbol(declaration) as INamedTypeSymbol;
            if (typeSymbol == null)
            {
                return;
            }

            // We cannot have multiple overlapping diagnostics of this id.
            var diagnostic = context.Diagnostics.Single();

            context.RegisterCodeFix(new MyCodeAction(SystemRuntimeAnalyzersResources.OverloadOperatorEqualsOnOverridingValueTypeEquals,
                                                     async ct => await ImplementOperatorEquals(context.Document, declaration, typeSymbol, ct).ConfigureAwait(false)),
                                    diagnostic);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:26,代码来源:OverloadOperatorEqualsOnOverridingValueTypeEquals.Fixer.cs


示例20: AddCodeFixWithNewPublicConstructor

    private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root,
      Diagnostic diagnostic, ClassDeclarationSyntax classNode)
    {
      // Generated from http://roslynquoter.azurewebsites.net/
      var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier)
        .WithModifiers(
          SyntaxFactory.TokenList(
            SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
        .WithParameterList(SyntaxFactory.ParameterList()
          .WithOpenParenToken(
            SyntaxFactory.Token(SyntaxKind.OpenParenToken))
          .WithCloseParenToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseParenToken)))
        .WithBody(SyntaxFactory.Block()
          .WithOpenBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.OpenBraceToken))
          .WithCloseBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation);
      var newClassNode = classNode.AddMembers(constructor);
      var newRoot = root.ReplaceNode(classNode, newClassNode);

      context.RegisterCodeFix(
        CodeAction.Create(
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription,
          _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic);
    }
开发者ID:JorgeArellano,项目名称:csla,代码行数:30,代码来源:CheckConstructorsAnalyzerPublicConstructorCodeFix.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CodeFixes.CodeFixProvider类代码示例发布时间:2022-05-26
下一篇:
C# CodeActions.CodeAction类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap