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


C# MethodDeclarationSyntax.WithModifiers方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax.WithModifiers方法的典型用法代码示例。如果您正苦于以下问题:C# MethodDeclarationSyntax.WithModifiers方法的具体用法?C# MethodDeclarationSyntax.WithModifiers怎么用?C# MethodDeclarationSyntax.WithModifiers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax的用法示例。


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

示例1: RemoveAsyncAwait

        private async Task<Document> RemoveAsyncAwait(Document document, MethodDeclarationSyntax methodDecl, CancellationToken cancellationToken)
        {
            MethodDeclarationSyntax newMethodDecl;

            // (1) Remove async keyword
            var asyncModifier = methodDecl.Modifiers.First(a => a.Kind() == SyntaxKind.AsyncKeyword);
            newMethodDecl = asyncModifier.HasLeadingTrivia 
                ? methodDecl.WithModifiers(methodDecl.Modifiers.Remove(asyncModifier)).WithLeadingTrivia(asyncModifier.LeadingTrivia)
                : methodDecl.WithModifiers(methodDecl.Modifiers.Remove(asyncModifier));

            // (2) If void, convert it to Task
            if (newMethodDecl.ReturnsVoid())
            {
                var newType = SyntaxFactory.ParseTypeName("System.Threading.Tasks.Task").WithAdditionalAnnotations(Simplifier.Annotation).WithTrailingTrivia(newMethodDecl.ReturnType.GetTrailingTrivia());
                newMethodDecl = newMethodDecl.WithReturnType(newType);
            }

            // (3) For all await expressions, remove await and insert return if there is none. 
            var awaitExprs = newMethodDecl.Body.DescendantNodes().OfType<AwaitExpressionSyntax>();

            List<SyntaxReplacementPair> pairs = new List<SyntaxReplacementPair>();

            foreach (var awaitExpr in awaitExprs)
            {
                SyntaxNode oldNode;
                SyntaxNode newNode;
                var newAwaitExpr = awaitExpr;
                // If there is some ConfigureAwait(false), remove it 
                var invoc = awaitExpr.Expression as InvocationExpressionSyntax;
                if (invoc != null)
                {
                    var expr = invoc.Expression as MemberAccessExpressionSyntax;

                    // TODO: Check whether it is ConfigureAwait(false) or ConfigureAwait(true);
                    if (expr != null && expr.Name.Identifier.ValueText == "ConfigureAwait")
                    {
                        newAwaitExpr = awaitExpr.ReplaceNode(awaitExpr.Expression, expr.Expression);
                    }
                }

                if (awaitExpr.Parent.Kind() == SyntaxKind.ReturnStatement)
                {
                    oldNode = awaitExpr;
                    newNode = newAwaitExpr.Expression.WithAdditionalAnnotations(Simplifier.Annotation);
                }
                else
                {
                    oldNode = awaitExpr.Parent;
                    newNode = SyntaxFactory.ReturnStatement(newAwaitExpr.Expression).WithAdditionalAnnotations(Formatter.Annotation).WithTrailingTrivia(oldNode.GetTrailingTrivia());
                }
                pairs.Add(new SyntaxReplacementPair(oldNode, newNode));
            }

            newMethodDecl = newMethodDecl.ReplaceAll(pairs);

            // (4) Replace the old method with the new one.
            var root = await document.GetSyntaxRootAsync().ConfigureAwait(false);
            var newRoot = root.ReplaceNode(methodDecl, newMethodDecl);
            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:modulexcite,项目名称:AsyncFixer,代码行数:60,代码来源:UnnecessaryAsyncFixer.cs

示例2: RegisterNewCodeFix

    private static void RegisterNewCodeFix(CodeFixContext context, SyntaxNode root, MethodDeclarationSyntax methodNode,
      SyntaxKind visibility, string description, Diagnostic diagnostic)
    {
      var publicModifier = methodNode.Modifiers.Where(_ => _.Kind() == SyntaxKind.PublicKeyword).First();
      var visibilityNode = SyntaxFactory.Token(publicModifier.LeadingTrivia, visibility,
        publicModifier.TrailingTrivia);
      var modifiers = methodNode.Modifiers.Replace(publicModifier, visibilityNode);
      var newwMethodNode = methodNode.WithModifiers(modifiers);
      var newRoot = root.ReplaceNode(methodNode, newwMethodNode);

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

示例3: ReplacePropertyModifierAsync

        private async Task<Document> ReplacePropertyModifierAsync(Document document, MethodDeclarationSyntax method, SyntaxKind methodModifier, CancellationToken cancellationToken)
        {
            var previousWhiteSpacesToken = SyntaxFactory.Token(method.GetLeadingTrivia(), SyntaxKind.StringLiteralToken, SyntaxTriviaList.Empty);

            var newProperty = method.WithModifiers(SyntaxTokenList.Create(previousWhiteSpacesToken)
            .Add(SyntaxFactory.Token(methodModifier))
            .Add(_whitespaceToken));

            if (method.Modifiers.Any(m => m.Kind() == SyntaxKind.VirtualKeyword))
            {
                newProperty = newProperty.AddModifiers(SyntaxFactory.Token(SyntaxKind.VirtualKeyword), _whitespaceToken);
            }

            return await ReplacePropertyInDocumentAsync(document, method, newProperty, cancellationToken);
        }
开发者ID:ChrisMaddock,项目名称:NUnitStaticAnalyzers,代码行数:15,代码来源:SetUpCodeFixProvider.cs

示例4: VisitMethodDeclaration

		/// <summary>
		///   Normalizes the <paramref name="declaration" />.
		/// </summary>
		public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax declaration)
		{
			_methodSymbol = declaration.GetMethodSymbol(SemanticModel);
			if (!_methodSymbol.ContainingType.IsComponent(SemanticModel) || !_methodSymbol.IsRequiredPort(SemanticModel))
				return declaration;

			var body = CreateBindingCode();
			var originalDeclaration = declaration;
			var index = declaration.Modifiers.IndexOf(SyntaxKind.ExternKeyword);
			var delegateFieldName = Syntax.LiteralExpression(GetBindingDelegateFieldName());
			var infoFieldName = Syntax.LiteralExpression(GetBinderFieldName());
			var defaultMethod = Syntax.LiteralExpression(GetUnboundPortAssignmentMethodName());

			declaration = declaration.WithModifiers(declaration.Modifiers.RemoveAt(index)).WithSemicolonToken(default(SyntaxToken));
			declaration = (MethodDeclarationSyntax)Syntax.AddAttribute<DebuggerHiddenAttribute>(declaration);
			declaration = (MethodDeclarationSyntax)Syntax.AddAttribute<BindingMetadataAttribute>(declaration,
				delegateFieldName, infoFieldName, defaultMethod);

			return declaration.WithBody(body).EnsureLineCount(originalDeclaration);
		}
开发者ID:isse-augsburg,项目名称:ssharp,代码行数:23,代码来源:RequiredPortNormalizer.cs

示例5: VisitMethodDeclaration

        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);

            // only public methods not marked as virtual
            if (node.Modifiers.Any(SyntaxKind.PublicKeyword) && !node.Modifiers.Any(SyntaxKind.VirtualKeyword))
            {
                var symbol = _compiler.GetSemanticModel(node.SyntaxTree).GetDeclaredSymbol(node);
                if (symbol.InheritsFrom<Controller>())
                {
                    Debug.WriteLine(
                        "R4MVC - Marking controller method {0} as virtual from {1}",
                        symbol.ToString(),
                        symbol.ContainingType?.ToString());
                    node = node.WithModifiers(SyntaxKind.VirtualKeyword);
                }
            }

            return node;
        }
开发者ID:kazuk,项目名称:R4MVC,代码行数:20,代码来源:ControllerRewriter.cs

示例6: OverrideMethod

 private MethodDeclarationSyntax OverrideMethod(MethodDeclarationSyntax method)
 {
     return method
         .WithModifiers(CSharp.TokenList(method
                 .Modifiers
                 .Where(modifier => modifier.Kind() != SyntaxKind.VirtualKeyword)
                 .Union(new[] { CSharp.Token(SyntaxKind.OverrideKeyword) })
                 .ToArray()))
         .WithBody(CSharp.Block()
             .WithStatements(CSharp.List(new[] {
                 contextCall.Get<StatementSyntax>(method
                     .ParameterList
                     .Parameters
                     .First()
                     .Type)
             })));
 }
开发者ID:mpmedia,项目名称:Excess,代码行数:17,代码来源:AntlrTool.cs

示例7: NormalizeExternMethod

		/// <summary>
		///     Normalizes the <paramref name="methodDeclaration" /> and adds the generated members.
		/// </summary>
		/// <param name="methodDeclaration">The method declaration that should be normalized.</param>
		private MethodDeclarationSyntax NormalizeExternMethod(MethodDeclarationSyntax methodDeclaration)
		{
			var originalDeclaration = methodDeclaration;
			var methodDelegate = CreateDelegate(methodDeclaration);
			var methodField = CreateField(methodDelegate);

			// Add the [Required] attribute if it is not already present
			if (!methodDeclaration.HasAttribute<RequiredAttribute>(SemanticModel))
			{
				methodDeclaration = methodDeclaration.RemoveTrivia();
				methodDeclaration = methodDeclaration.WithAttributeLists(methodDeclaration.AttributeLists.Add(_requiredAttribute.WithTrailingSpace()));
			}

			// Remove the 'extern' keyword from the method
			var externIndex = methodDeclaration.Modifiers.IndexOf(SyntaxKind.ExternKeyword);
			methodDeclaration = methodDeclaration.WithModifiers(methodDeclaration.Modifiers.RemoveAt(externIndex));

			// Add the [DebuggerHidden] attribute if it is not already present
			if (!originalDeclaration.HasAttribute<DebuggerHiddenAttribute>(SemanticModel))
				methodDeclaration = methodDeclaration.WithAttributeLists(methodDeclaration.AttributeLists.Add(_debuggerHiddenAttribute));

			// Replace the method's body and ensure that we don't modify the line count of the containing type
			methodDeclaration = AddBackingFieldAttribute(methodDeclaration);
			methodDeclaration = ReplaceBodyWithDelegateInvocation(methodDeclaration);
			methodDeclaration = methodDeclaration.NormalizeWhitespace();
			methodDeclaration = methodDeclaration.WithTrivia(originalDeclaration);

			++_portCount;
			AddMembers(originalDeclaration.GetMethodSymbol(SemanticModel).ContainingType, methodField, methodDelegate);
			return methodDeclaration.EnsureLineCount(originalDeclaration);
		}
开发者ID:cubeme,项目名称:safety-sharp,代码行数:35,代码来源:MethodNormalizer.cs


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