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


C# SyntaxGenerator.ReturnStatement方法代码示例

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


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

示例1: GetInvertedStatement

 private SyntaxNode GetInvertedStatement(
     SyntaxGenerator generator, IMethodSymbol containingOperator, Compilation compilation)
 {
     if (containingOperator.Name == WellKnownMemberNames.EqualityOperatorName)
     {
         return generator.ReturnStatement(
             generator.LogicalNotExpression(
                 generator.ValueEqualsExpression(
                     generator.IdentifierName(containingOperator.Parameters[0].Name),
                     generator.IdentifierName(containingOperator.Parameters[1].Name))));
     }
     else if (containingOperator.Name == WellKnownMemberNames.InequalityOperatorName)
     {
         return generator.ReturnStatement(
             generator.LogicalNotExpression(
                 generator.ValueNotEqualsExpression(
                     generator.IdentifierName(containingOperator.Parameters[0].Name),
                     generator.IdentifierName(containingOperator.Parameters[1].Name))));
     }
     else
     {
         // If it's a  <   >   <=   or  >=   operator then we can't simply invert a call
         // to the existing operator.  i.e. the body of the "<" method should *not* be:
         //    return !(a > b);
         // Just provide a throwing impl for now.
         return generator.DefaultMethodStatement(compilation);
     }
 }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:28,代码来源:OperatorsShouldHaveSymmetricalOverloads.Fixer.cs

示例2: Fix

        private static async Task<Document> Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            SyntaxNode node = root.FindNode(context.Span);
            Diagnostic diagnostic = context.Diagnostics.First();
            switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
            {
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.AddAlternateText:
                    SyntaxNode methodDeclaration = generator.GetDeclaration(node, DeclarationKind.Operator) ?? generator.GetDeclaration(node, DeclarationKind.ConversionOperator);
                    var operatorOverloadSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);
                    INamedTypeSymbol typeSymbol = operatorOverloadSymbol.ContainingType;

                    // For C# the following `typeDeclarationSyntax` and `typeDeclaration` nodes are identical, but for VB they're different so in
                    // an effort to keep this as language-agnostic as possible, the heavy-handed approach is used.
                    SyntaxNode typeDeclarationSyntax = typeSymbol.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
                    SyntaxNode typeDeclaration = generator.GetDeclaration(typeDeclarationSyntax,
                        typeSymbol.TypeKind == TypeKind.Struct ? DeclarationKind.Struct : DeclarationKind.Class);

                    SyntaxNode addedMember;
                    IEnumerable<SyntaxNode> bodyStatements = generator.DefaultMethodBody(semanticModel.Compilation);
                    if (OperatorOverloadsHaveNamedAlternatesAnalyzer.IsPropertyExpected(operatorOverloadSymbol.Name))
                    {
                        // add a property
                        addedMember = generator.PropertyDeclaration(
                            name: OperatorOverloadsHaveNamedAlternatesAnalyzer.IsTrueText,
                            type: generator.TypeExpression(SpecialType.System_Boolean),
                            accessibility: Accessibility.Public,
                            modifiers: DeclarationModifiers.ReadOnly,
                            getAccessorStatements: bodyStatements);
                    }
                    else
                    {
                        // add a method
                        ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);

                        if (expectedSignature.Name == "CompareTo" && operatorOverloadSymbol.ContainingType.TypeKind == TypeKind.Class)
                        {
                            var nullCheck = generator.IfStatement(
                                generator.InvocationExpression(
                                    generator.IdentifierName("ReferenceEquals"),
                                    generator.IdentifierName(expectedSignature.Parameters.First().Item1),
                                    generator.NullLiteralExpression()),
                                new[]
                                {
                                    generator.ReturnStatement(generator.LiteralExpression(1))
                                });

                            bodyStatements = new[] {nullCheck}.Concat(bodyStatements);
                        }

                        addedMember = generator.MethodDeclaration(
                            name: expectedSignature.Name,
                            parameters: expectedSignature.Parameters.Select(p => generator.ParameterDeclaration(p.Item1, generator.TypeExpression(p.Item2))),
                            returnType: generator.TypeExpression(expectedSignature.ReturnType),
                            accessibility: Accessibility.Public,
                            modifiers: expectedSignature.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None,
                            statements: bodyStatements);
                    }

                    SyntaxNode newTypeDeclaration = generator.AddMembers(typeDeclaration, addedMember);
                    return context.Document.WithSyntaxRoot(root.ReplaceNode(typeDeclaration, newTypeDeclaration));
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.FixVisibilityText:
                    SyntaxNode badVisibilityNode = generator.GetDeclaration(node, DeclarationKind.Method) ?? generator.GetDeclaration(node, DeclarationKind.Property);
                    ISymbol badVisibilitySymbol = semanticModel.GetDeclaredSymbol(badVisibilityNode, cancellationToken);
                    SymbolEditor symbolEditor = SymbolEditor.Create(context.Document);
                    ISymbol newSymbol = await symbolEditor.EditOneDeclarationAsync(badVisibilitySymbol,
                        (documentEditor, syntaxNode) => documentEditor.SetAccessibility(badVisibilityNode, Accessibility.Public), cancellationToken).ConfigureAwait(false);
                    Document newDocument = symbolEditor.GetChangedDocuments().Single();
                    SyntaxNode newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                    return context.Document.WithSyntaxRoot(newRoot);
                default:
                    return context.Document;
            }
        }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:73,代码来源:OperatorOverloadsHaveNamedAlternates.Fixer.cs

示例3: GetMethodStatementsSyntax


//.........这里部分代码省略.........
                if (parameter.RefKind == RefKind.Out)
                {
                    yield return syntaxGenerator
                        .LocalDeclarationStatement(
                            syntaxGenerator.TypeExpression(parameter.Type),
                            GetNameForParameter(methodSymbol, parameter));
                }
                else if (parameter.RefKind == RefKind.Ref)
                {
                    yield return syntaxGenerator
                        .LocalDeclarationStatement(
                            GetNameForParameter(methodSymbol, parameter),
                            initializer: syntaxGenerator.DefaultExpression(syntaxGenerator.TypeExpression(parameter.Type)));
                }
            }

            var arguments = methodSymbol
                .Parameters
                .Select(x =>
                    syntaxGenerator
                        .Argument(
                            x.RefKind,
                            syntaxGenerator.IdentifierName(GetNameForParameter(methodSymbol, x))))
                .ToList();

            var typeArguments = methodSymbol
                .TypeArguments
                .Select(x => syntaxGenerator.TypeExpression(x))
                .ToList();

            var lambdaParameterName = GetUniqueName(methodSymbol);

            var lambdaInvocation = syntaxGenerator
                .MemberAccessExpression(
                    syntaxGenerator.IdentifierName(lambdaParameterName),
                    methodSymbol.Name);

            if (typeArguments.Count > 0)
            {
                lambdaInvocation = syntaxGenerator
                    .WithTypeArguments(
                        lambdaInvocation,
                        typeArguments);
            }

            // GENERATED CODE (for every ref or out parameter):
            //
            //     someOutParameter = this.GetOutParameterValue<string>(x => x.TheMethod(out someOutParameter), parameterIndex: 0);
            //     someRefParameter = this.GetRefParameterValue<int>(x => x.TheMethod(ref someRefParameter), parameterIndex: 0);
            for (var i = 0; i < methodSymbol.Parameters.Length; ++i)
            {
                var parameter = methodSymbol.Parameters[i];

                if (parameter.RefKind == RefKind.Out || parameter.RefKind == RefKind.Ref)
                {
                    var nameOfMethodToCall = parameter.RefKind == RefKind.Out ? "GetOutParameterValue" : "GetRefParameterValue";

                    yield return syntaxGenerator
                        .AssignmentStatement(
                            syntaxGenerator.IdentifierName(parameter.Name),
                            syntaxGenerator
                            .InvocationExpression(
                                syntaxGenerator.MemberAccessExpression(
                                    syntaxGenerator.ThisExpression(),
                                    syntaxGenerator.GenericName(
                                        nameOfMethodToCall,
                                        typeArguments: syntaxGenerator.TypeExpression(parameter.Type))),
                                        arguments: new[]
                                        {
                                            syntaxGenerator.ValueReturningLambdaExpression(
                                                lambdaParameterName,
                                                syntaxGenerator.InvocationExpression(
                                                    lambdaInvocation,
                                                    arguments: arguments)),
                                                syntaxGenerator.LiteralExpression(i)
                                        }));
                }
            }

            // GENERATED CODE:
            //
            //     [return] this.Apply(x => x.SomeMethod(param1, param2));
            var applyInvocation = syntaxGenerator
                .InvocationExpression(
                    syntaxGenerator.MemberAccessExpression(
                        syntaxGenerator.ThisExpression(),
                        "Apply"),
                    syntaxGenerator.ValueReturningLambdaExpression(
                        lambdaParameterName,
                        syntaxGenerator.InvocationExpression(
                            lambdaInvocation,
                            arguments: arguments)));

            if (!methodSymbol.ReturnsVoid)
            {
                applyInvocation = syntaxGenerator.ReturnStatement(applyInvocation);
            }
            
            yield return applyInvocation;
        }
开发者ID:modulexcite,项目名称:PCLMock,代码行数:101,代码来源:Generator.cs

示例4: GetPropertyGetAccessorsSyntax

        private static IEnumerable<SyntaxNode> GetPropertyGetAccessorsSyntax(
            SyntaxGenerator syntaxGenerator,
            SemanticModel semanticModel,
            IPropertySymbol propertySymbol)
        {
            if (propertySymbol.GetMethod == null)
            {
                yield break;
            }

            var lambdaParameterName = GetUniqueName(propertySymbol);

            if (!propertySymbol.IsIndexer)
            {
                // GENERATED CODE:
                //
                //     return this.Apply(x => x.PropertyName);
                yield return syntaxGenerator
                    .ReturnStatement(
                        syntaxGenerator.InvocationExpression(
                            syntaxGenerator.MemberAccessExpression(
                                syntaxGenerator.ThisExpression(),
                                "Apply"),
                            syntaxGenerator.ValueReturningLambdaExpression(
                                lambdaParameterName,
                                syntaxGenerator.MemberAccessExpression(
                                    syntaxGenerator.IdentifierName(lambdaParameterName),
                                    syntaxGenerator.IdentifierName(propertySymbol.Name)))));
            }
            else
            {
                // GENERATED CODE:
                //
                //     return this.Apply(x => x[first, second]);
                var arguments = propertySymbol
                    .Parameters
                    .Select(x => syntaxGenerator.Argument(syntaxGenerator.IdentifierName(x.Name)))
                    .ToList();

                yield return syntaxGenerator
                    .ReturnStatement(
                        syntaxGenerator.InvocationExpression(
                            syntaxGenerator.MemberAccessExpression(
                                syntaxGenerator.ThisExpression(),
                                "Apply"),
                            syntaxGenerator.ValueReturningLambdaExpression(
                                lambdaParameterName,
                                syntaxGenerator.ElementAccessExpression(
                                    syntaxGenerator.IdentifierName(lambdaParameterName),
                                    arguments))));
            }
        }
开发者ID:modulexcite,项目名称:PCLMock,代码行数:52,代码来源:Generator.cs

示例5: CreateGetProxyMethod

 private SyntaxNode CreateGetProxyMethod(Compilation compilation, SyntaxGenerator g, INamedTypeSymbol proxyInterface, GenerationNameTable nameTable, bool isAsync)
 {
    //private IProxy GetProxy()
    //{
    //   EnsureProxy();
    //   return m_cachedProxy;
    //}
    return g.MethodDeclaration(
       isAsync ? nameTable[MemberNames.GetProxyAsyncMethod] : nameTable[MemberNames.GetProxyMethod],
       returnType: g.TypeExpression(isAsync ? compilation.RequireType(typeof(Task<>)).Construct(proxyInterface) : proxyInterface),
       accessibility: Accessibility.Private,
       modifiers: isAsync ? DeclarationModifiers.Async : DeclarationModifiers.None,
       statements: new SyntaxNode[]
       {
          g.ExpressionStatement(
             AwaitExpressionIfAsync(g, isAsync,
                g.InvocationExpression(
                   g.MemberAccessExpression(
                      g.ThisExpression(),
                      isAsync ? nameTable[MemberNames.EnsureProxyAsyncMethod] : nameTable[MemberNames.EnsureProxyMethod]
                   )
                )
             )
          ),
          g.ReturnStatement(
             g.MemberAccessExpression(
                g.ThisExpression(),
                nameTable[MemberNames.CachedProxyField]
             )
          )
       }
    );
 }
开发者ID:modulexcite,项目名称:WcfClientProxyGenerator,代码行数:33,代码来源:ClientProxyGenerator.ClientClass.cs

示例6: CreateProxyInvocationStatement

      private SyntaxNode CreateProxyInvocationStatement(Compilation compilation, SyntaxGenerator g, GenerationNameTable nameTable, IMethodSymbol sourceMethod)
      {
         bool isAsync = ReturnsTask(compilation, sourceMethod);
         bool isVoid = IsVoid(compilation, sourceMethod);

         // proxy.Method(arg1, arg2, ...);
         SyntaxNode invocation = g.InvocationExpression(
                                    g.MemberAccessExpression(
                                       g.IdentifierName(nameTable[MemberNames.ProxyVariable]),
                                       sourceMethod.Name
                                    ),
                                    sourceMethod.Parameters.Select(p => g.IdentifierName(p.Name))
                                 );

         if (isAsync)
         {
            // await proxy.Method(arg1, arg2, ...).ConfigureAwait(false);
            invocation =
               g.AwaitExpression(
                  g.InvocationExpression(
                     g.MemberAccessExpression(
                        invocation,
                        "ConfigureAwait"
                     ),
                     g.FalseLiteralExpression()
                  )
               );
         }

         if (isVoid)
         {
            invocation = g.ExpressionStatement(invocation);
         }
         else
         {
            invocation = g.ReturnStatement(invocation);
         }

         return invocation;

      }
开发者ID:modulexcite,项目名称:WcfClientProxyGenerator,代码行数:41,代码来源:ClientProxyGenerator.ClientClass.cs

示例7: GenerateProxyClass

      public ClassDeclarationSyntax GenerateProxyClass(SemanticModel semanticModel, SyntaxGenerator generator, INamedTypeSymbol sourceProxyInterface, string name, Accessibility accessibility, bool suppressWarningComments, MemberAccessibility constructorAccessibility, out IEnumerable<IMethodSymbol> sourceConstructors)
      {
         if (name == null)
         {
            if (sourceProxyInterface.Name.StartsWith("I"))
               name = sourceProxyInterface.Name.Substring(1) + "Proxy";
            else
               name = sourceProxyInterface.Name + "Proxy";
         }

         var compilation = semanticModel.Compilation;

         // Resolve the callback contract if any
         ITypeSymbol serviceContractAttributeType = compilation.RequireTypeByMetadataName("System.ServiceModel.ServiceContractAttribute");
         AttributeData serviceContractAttribute = sourceProxyInterface.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(serviceContractAttributeType));
         if (serviceContractAttribute == null)
            throw new CodeGeneratorException(sourceProxyInterface, $"The interface {sourceProxyInterface.Name} is not decorated with ServiceContractAttribute.");

         ITypeSymbol callbackContractType;
         var callbackContractArg = serviceContractAttribute.NamedArguments.FirstOrDefault(arg => arg.Key.Equals("CallbackContract"));
         if (callbackContractArg.Key != null)
            callbackContractType = callbackContractArg.Value.Value as ITypeSymbol;
         else
            callbackContractType = null;

         // Resolve the base type (ClientBase or DuplexClientBase depending on whether a CallbackContract exists or not)
         INamedTypeSymbol baseType;
         if (callbackContractType != null)
         {
            baseType = compilation.RequireTypeByMetadataName("System.ServiceModel.DuplexClientBase`1").Construct(sourceProxyInterface);
         }
         else
         {
            baseType = compilation.RequireTypeByMetadataName("System.ServiceModel.ClientBase`1").Construct(sourceProxyInterface);
         }

         // Create class declaration
         SyntaxNode targetClass = generator.ClassDeclaration(name, accessibility: accessibility, baseType: generator.TypeExpression(baseType), interfaceTypes: new[] { generator.TypeExpression(sourceProxyInterface) });

         targetClass = generator.AddWarningCommentIf(!suppressWarningComments, targetClass);


         // Copy constructors from base class.
         sourceConstructors = baseType.Constructors.Where(ctor => ctor.DeclaredAccessibility != Accessibility.Private).ToImmutableArray();

         foreach (var baseCtor in sourceConstructors)
         {
            var targetCtor = generator.ConstructorDeclaration(baseCtor, baseCtor.Parameters.Select(p => generator.Argument(generator.IdentifierName(p.Name))));

            targetCtor = generator.AddWarningCommentIf(!suppressWarningComments, targetCtor);

            targetCtor = generator.WithAccessibility(targetCtor, ToAccessibility(constructorAccessibility));
            targetClass = generator.AddMembers(targetClass, targetCtor.AddNewLineTrivia());
         }

         foreach (IMethodSymbol sourceMethod in GetOperationContractMethods(semanticModel.Compilation, sourceProxyInterface))
         {
            SyntaxNode targetMethod = generator.MethodDeclaration(sourceMethod);

            targetMethod = generator.AddWarningCommentIf(!suppressWarningComments, targetMethod);

            targetMethod = generator.WithModifiers(targetMethod, DeclarationModifiers.None);

            bool isVoid = sourceMethod.ReturnType.SpecialType == SpecialType.System_Void;
            targetMethod = targetMethod.AddNewLineTrivia().AddNewLineTrivia();

            var expression = generator.InvocationExpression(
               generator.MemberAccessExpression(
                  generator.MemberAccessExpression(
                     generator.BaseExpression(),
                     "Channel"
                  ),
                  sourceMethod.Name
               ),
               sourceMethod.Parameters.Select(p => generator.IdentifierName(p.Name)).ToArray()
            );

            SyntaxNode statement;
            if (!isVoid)
               statement = generator.ReturnStatement(expression);
            else
               statement = generator.ExpressionStatement(expression);

            targetMethod = generator.WithStatements(targetMethod,
               new[]
               {
                  statement
               }
            );
            targetClass = generator.AddMembers(targetClass, targetMethod.AddNewLineTrivia());
         }

         return (ClassDeclarationSyntax)targetClass;
      }
开发者ID:modulexcite,项目名称:WcfClientProxyGenerator,代码行数:94,代码来源:ClientProxyGenerator.ProxyClass.cs


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