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

C# Syntax.MethodDeclarationSyntax类代码示例

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

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



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

示例1: UpdateMainDocument

 private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
 {
     var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
     SyntaxNode newRoot;
     if (mainDocGroup == null)
     {
         newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
     }
     else
     {
         var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
         newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
         newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
         foreach (var diagnosticNode in diagnosticNodes)
         {
             var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
             var tokenParent = token.Parent;
             if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
             var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
             if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
             var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
             if (memberAccess == null) continue;
             var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
         }
     }
     var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
     return newSolution;
 }
开发者ID:nagyistoce,项目名称:code-cracker,代码行数:30,代码来源:MakeMethodStaticCodeFixProvider.cs


示例2: GetPreconditions

        public static PreconditionsBlock GetPreconditions(MethodDeclarationSyntax method, SemanticModel semanticModel)
        {
            Contract.Requires(method != null);

            var preconditions = new List<IfThrowPrecondition>();

            // Precondition block ends when something exception precondition check is met.
            foreach (var statement in method.Body.Statements)
            {
                // Currently, If-throw precondition means that
                // if statement has only one statement in the if block
                // and this statement is a throw of type ArgumentException
                var ifThrowStatement = statement as IfStatementSyntax;
                if (ifThrowStatement == null) break;

                var block = ifThrowStatement.Statement as BlockSyntax;
                if (block != null && block.Statements.Count != 1) break;

                var throwStatementCandidate = block != null ? block.Statements[0] : ifThrowStatement.Statement;

                // The only valid case (when the processing should keep going)
                // is when the if block has one statement and that statment is a throw of ArgumentException
                if (IsThrowArgumentExceptionStatement(throwStatementCandidate, semanticModel))
                {
                    preconditions.Add(new IfThrowPrecondition(statement, (ThrowStatementSyntax) throwStatementCandidate));
                }
                else
                {
                    break;
                }
            }

            return new PreconditionsBlock(preconditions);
        }
开发者ID:SergeyTeplyakov,项目名称:ErrorProne.NET,代码行数:34,代码来源:PreconditionsBlock.cs


示例3: FindError

		protected override string FindError(MethodDeclarationSyntax method)
		{
			var statements = method.Body.Statements;
			return statements.Count != 1 
				|| !(statements.Single() is ReturnStatementSyntax) 
				? ShouldBeSingleMethodMessage : null;
		}
开发者ID:kontur-edu,项目名称:uLearn,代码行数:7,代码来源:ICSharpSolutionValidator.cs


示例4: CreateParameterClass

 private static ClassDeclarationSyntax CreateParameterClass(string newNameClass, MethodDeclarationSyntax oldMethod)
 {
     var properties = CreateProperties(oldMethod);
     return SyntaxFactory.ClassDeclaration(newNameClass)
         .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(properties))
         .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:7,代码来源:ParameterRefactoryCodeFixProvider.cs


示例5: ReturnVoidAsync

        private async Task<Document> ReturnVoidAsync(Document document, MethodDeclarationSyntax method, CancellationToken cancellationToken)
        {
            var newStatements = new List<StatementSyntax>();
            foreach (var s in method.Body.Statements)
            {
                if (s is ReturnStatementSyntax)
                {
                    continue;
                }
                else
                    newStatements.Add(s);
            }

            var newMethodDeclaration =
                SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void").WithLeadingTrivia(method.ReturnType.GetLeadingTrivia()).WithTrailingTrivia(method.ReturnType.GetTrailingTrivia()), method.Identifier)
                .AddModifiers(method.Modifiers.ToArray())
                .WithLeadingTrivia(method.GetLeadingTrivia())
                .WithBody(SyntaxFactory.Block(newStatements))
                ;

            var root = await document.GetSyntaxRootAsync();
            var newRoot = root.ReplaceNode(method, newMethodDeclaration);

            return document.WithSyntaxRoot(newRoot);
        }
开发者ID:marcoparenzan,项目名称:CSharpDay2015,代码行数:25,代码来源:AggregateMethodMustReturnVoidOrSelfCodeFixProvider.cs


示例6: VisitMethodDeclaration

 public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax methodSyntax)
 {
     var leadingTrivia = methodSyntax.Identifier.LeadingTrivia;
     var trailingTriva = methodSyntax.Identifier.TrailingTrivia;
     return methodSyntax.ReplaceToken(methodSyntax.Identifier,
         SyntaxFactory.Identifier(leadingTrivia, ToCamelCase(methodSyntax.Identifier.ValueText), trailingTriva));
 }
开发者ID:nhabuiduc,项目名称:TypescriptSyntaxPaste,代码行数:7,代码来源:MakeMemberCamelCase.cs


示例7: VisitMethodDeclaration

 public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
 {
     if (RequiresNullChecks(node.AttributeLists))
     {
         AddMessage(node, $"method {node.Identifier} needs null checks");
     }
 }
开发者ID:jimdeselms,项目名称:codeformatter,代码行数:7,代码来源:NullCheckerValidation.cs


示例8: VisitMethodDeclaration

		public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
		{
			var visibilityTokens = node.DescendantTokens(_ => true)
				.Where(_ => _.IsKind(SyntaxKind.PublicKeyword) ||
					_.IsKind(SyntaxKind.PrivateKeyword) ||
					_.IsKind(SyntaxKind.ProtectedKeyword) ||
					_.IsKind(SyntaxKind.InternalKeyword)).ToImmutableList();

			if (!visibilityTokens.Any(_ => _.IsKind(SyntaxKind.PublicKeyword)))
			{
				var tokenPosition = 0;

				var newMethod = node.ReplaceTokens(visibilityTokens,
					(_, __) =>
					{
						tokenPosition++;

						return tokenPosition == 1 ?
							SyntaxFactory.Token(
								_.LeadingTrivia,
								SyntaxKind.PublicKeyword,
								_.TrailingTrivia) :
							new SyntaxToken();
					});
				return newMethod;
			}
			else
			{
				return node;
			}
		}
开发者ID:JasonBock,项目名称:CompilerAPIBook,代码行数:31,代码来源:MethodRewriter.cs


示例9: 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


示例10: Run

 public void Run(object testObject, MethodDeclarationSyntax method, SemanticModel semanticModel)
 {
     _semanticModel = semanticModel;
     ExecuteSetup(testObject, method);
     ExecuteTest(testObject, method);
     ExecuteTearDown(testObject, method);
 }
开发者ID:andrecarlucci,项目名称:tddanalyzer,代码行数:7,代码来源:TestFramework.cs


示例11: VisitMethodDeclaration

 public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
 {
     var parameterTokens = node.ParameterList.Parameters.Select(p => p.Identifier);
     tracker.AddIdentifiers(parameterTokens);
     Visit(node.Body);
     tracker.RemoveIdentifiers(parameterTokens);
 }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:7,代码来源:LocalConflictVisitor.cs


示例12: CalculateForMethod

        public CoverageResult CalculateForMethod(string projectName, MethodDeclarationSyntax method)
        {
            var projects = _testExplorer.GetUnignoredTestProjectsWithCoveredProjectsAsync().Result;
            var project = projects.FirstOrDefault(x => x.Name == projectName);

            if (project == null)
                return new CoverageResult(new LineCoverage[0]);

            var rewritter = new SolutionRewriter(new RewrittenDocumentsStorage(), _auditVariablesRewriter);
            RewrittenDocument rewrittenDocument = rewritter.RewriteDocumentWithAssemblyInfo(project, projects, method.SyntaxTree.FilePath, method.SyntaxTree.ToString());

            LineCoverage[] coverage = null;

            using (var appDomainTestExecutorScriptEngine = new AppDomainTestExecutorScriptEngine())
            {
                var lineCoverageCalc = new LineCoverageCalc(_testExplorer, new RoslynCompiler(),
                    new TestRunner(new NUnitTestExtractor(), appDomainTestExecutorScriptEngine, _solutionExplorer));

                coverage = lineCoverageCalc.CalculateForMethod(project, rewrittenDocument, method);
            }

            _coverageStore.Append(coverage);

            return new CoverageResult(coverage);
        }
开发者ID:pzielinski86,项目名称:RuntimeTestCoverage,代码行数:25,代码来源:SolutionCoverageEngine.cs


示例13: VisitMethodDeclaration

        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            // Not the correct way of getting rid of compiler generated getter/setter
            if (node.AttributeLists.Any(attrList =>
                attrList.Attributes.Any(attr =>
                    attr.Name.ToFullString().Contains("CompilerGeneratedAttribute")))||
                node.Identifier.ToFullString().StartsWith("get_") ||
                node.Identifier.ToFullString().StartsWith("set_") ||
                node.Identifier.ToFullString().StartsWith("add_")||
                node.Identifier.ToFullString().StartsWith("remove_"))
            {
                return null;
            }

            return base.VisitMethodDeclaration(
                node.Update(
                    node.AttributeLists,
                    SyntaxFactory.TokenList(),
                    UpdateReturnType(node.ReturnType),
                    node.ExplicitInterfaceSpecifier,
                    node.Identifier,
                    UpdateTypeParameterList(node.TypeParameterList),
                    UpdateParameterList(node.ParameterList),
                    node.ConstraintClauses,
                    UpdateMethodBody(node.Body, node.ReturnType, node.ParameterList),
                    node.SemicolonToken
                ));
        }
开发者ID:herskinduk,项目名称:AutoWrapping,代码行数:28,代码来源:RoslynTypeRewriter.cs


示例14: HandleMethod

        private Diagnostic HandleMethod(MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration.ExpressionBody != null)
            {
                return null;
            }

            if (methodDeclaration.DescendantNodesAndTokensAndSelf().Any(x => x.GetLeadingTrivia().Concat(x.GetTrailingTrivia()).Any(y => !y.IsWhitespaceTrivia())))
            {
                return null;
            }

            if (methodDeclaration.Body?.Statements.Count != 1)
            {
                return null;
            }

            var statement = methodDeclaration.Body.Statements.FirstOrDefault();
            var returnStatement = statement?.DescendantNodesAndSelf().OfType<ReturnStatementSyntax>().FirstOrDefault();
            if (returnStatement == null)
            {
                return null;
            }

            return Diagnostic.Create(Rule, returnStatement.GetLocation(), "Method", methodDeclaration.Identifier.ValueText);
        }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:26,代码来源:SimplifyExpressionBodiedMemberAnalyzer.cs


示例15: RunTest

        public LineCoverage[] RunTest(Project project,
            RewrittenDocument rewrittenDocument,
            MethodDeclarationSyntax method,
            ISemanticModel semanticModel,
            string[] rewrittenAssemblies)
        {
            var testClass = method.GetParentClass();
            var rewrittenTestClass =
                rewrittenDocument.SyntaxTree
                    .GetRoot()
                    .DescendantNodes()
                    .OfType<ClassDeclarationSyntax>().First(x => x.Identifier.ToString() == testClass.Identifier.ToString());

            var fixtureDetails = _testsExtractor.GetTestFixtureDetails(rewrittenTestClass, semanticModel);
            var allReferences = _solutionExplorer.GetAllProjectReferences(project.Name);

            fixtureDetails.Cases.RemoveAll(x => x.MethodName != method.Identifier.ToString());

            if (fixtureDetails.Cases.Count == 0)
                return null;

            var compiledTestInfo = new CompiledTestFixtureInfo
            {
                AllReferences = allReferences.Union(rewrittenAssemblies).ToArray(),
                TestDocumentPath = rewrittenDocument.DocumentPath,
                SemanticModel = semanticModel
            };

            var coverage = RunTestFixture(fixtureDetails, compiledTestInfo, project.Name);

            return coverage;
        }
开发者ID:pzielinski86,项目名称:RuntimeTestCoverage,代码行数:32,代码来源:TestRunner.cs


示例16: AnalyzeMethodCodeBlock

 private void AnalyzeMethodCodeBlock(CodeBlockAnalysisContext context, MethodDeclarationSyntax methodDeclarationSyntax)
 {
     if (HasMultipleIndentations(methodDeclarationSyntax.Body))
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclarationSyntax.Identifier.GetLocation(), methodDeclarationSyntax.Identifier.Text));
     }
 }
开发者ID:johannes-schmitt,项目名称:DaVinci,代码行数:7,代码来源:Oc1UseOneLevelOfIndentationPerMethod.cs


示例17: RepairXmlCommentAsync

        private async Task<Document> RepairXmlCommentAsync(Document document, MethodDeclarationSyntax methodSyntax, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var methodSymbol = model.GetDeclaredSymbol(methodSyntax);

            var xml = methodSymbol.GetDocumentationCommentXml();

            var documentTrivia = methodSyntax.GetLeadingTrivia().Where(n => n.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia).Last();

            var documentText = documentTrivia.ToFullString().TrimEnd();
            var invalidXml = Regex.Replace(documentText, @"^\s*///", "", RegexOptions.Multiline);

            var newXml = RpairXml(invalidXml);

            var newDocumentCommentText = Regex.Replace(newXml, @"^", "///", RegexOptions.Multiline) + "\r\n";

            var newDocumentTrivia = SyntaxFactory.ParseLeadingTrivia(newDocumentCommentText)[0];

            var newRoot = root.ReplaceTrivia(documentTrivia, newDocumentTrivia.WithAdditionalAnnotations(Formatter.Annotation));

            var newDocument = document.WithSyntaxRoot(newRoot);

            return newDocument;
        }
开发者ID:miya2000,项目名称:DocumentationCommentAnalyzer,代码行数:26,代码来源:DocumentationCommentAnalyzerCodeFixProvider.cs


示例18: IsMethodAttributeAnException

        private static bool IsMethodAttributeAnException(MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration == null) return false;

            foreach (var attributeList in methodDeclaration.AttributeLists)
            {
                foreach (var attribute in attributeList.Attributes)
                {
                    var identifierName = attribute.Name as IdentifierNameSyntax;
                    string nameText = null;
                    if (identifierName != null)
                    {
                        nameText = identifierName?.Identifier.Text;
                    }
                    else
                    {
                        var qualifiedName = attribute.Name as QualifiedNameSyntax;
                        if (qualifiedName != null)
                            nameText = qualifiedName.Right?.Identifier.Text;
                    }
                    if (nameText == null) continue;
                    if (IsExcludedAttributeName(nameText)) return true;
                }
            }
            return false;
        }
开发者ID:julianosaless,项目名称:code-cracker,代码行数:26,代码来源:RemovePrivateMethodNeverUsedAnalyzer.cs


示例19: DetectBlockingAsyncCallers

		public void DetectBlockingAsyncCallers(MethodDeclarationSyntax node)
		{
			var symbol = SemanticModel.GetDeclaredSymbol(node);
			if (symbol != null)
			{
				foreach (var refs in SymbolFinder.FindReferencesAsync(symbol, SourceFile.Project.Solution).Result)
				{
					foreach (var loc in refs.Locations)
					{
						var textSpan = loc.Location.SourceSpan;
						var callerNode = loc.Document.GetSyntaxRootAsync().Result.DescendantNodes(textSpan).FirstOrDefault(n => textSpan.Contains(n.Span));
						var callerText = loc.Document.GetTextAsync().Result.Lines.ElementAt(loc.Location.GetLineSpan().StartLinePosition.Line).ToString();
						if (callerText.Contains(".Wait()")) // caller.Contains(".Result")
						{
							Logs.TempLog5.Info("Blocking Caller Name: " + callerText.Trim() + " from this file: " + loc.Document.FilePath);
							var temp = callerNode != null ? callerNode.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault() : null;
							if (temp != null)
							{
								Logs.TempLog5.Info("Blocking Caller Method Node: " + temp.ToLog());
								if (temp.IsAsync())
								{
									Logs.TempLog5.Info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
								}
							}

							Logs.TempLog5.Info("Async method Callee from this file " + SourceFile.FilePath + node.ToLog()+ Logs.Break);
						}
					}
				}
			}
		}
开发者ID:modulexcite,项目名称:CSharpAnalyzer,代码行数:31,代码来源:AsyncAwaitAntiPatternsWalker.cs


示例20: TestSetup

        public void TestSetup()
        {
            syntaxTree = CSharpSyntaxTree.ParseText(Source);

            ifMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "IfMethod");
            switchMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "SwitchMethod");
        }
开发者ID:shrknt35,项目名称:sonarlint-vs,代码行数:7,代码来源:NavigationHelperTest.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Syntax.NameSyntax类代码示例发布时间:2022-05-26
下一篇:
C# Syntax.LocalDeclarationStatementSyntax类代码示例发布时间: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