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


C# Syntax.VariableDeclarationSyntax类代码示例

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


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

示例1: IsReportable

        private bool IsReportable(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel)
        {
            bool result;
            TypeSyntax variableTypeName = variableDeclaration.Type;
            if (variableTypeName.IsVar)
            {
                // Implicitly-typed variables cannot have multiple declarators. Short circuit if it does.
                bool hasMultipleVariables = variableDeclaration.Variables.Skip(1).Any();
                if(hasMultipleVariables == false)
                {
                    // Special case: Ensure that 'var' isn't actually an alias to another type. (e.g. using var = System.String).
                    IAliasSymbol aliasInfo = semanticModel.GetAliasInfo(variableTypeName);
                    if (aliasInfo == null)
                    {
                        // Retrieve the type inferred for var.
                        ITypeSymbol type = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;

                        // Special case: Ensure that 'var' isn't actually a type named 'var'.
                        if (type.Name.Equals("var", StringComparison.Ordinal) == false)
                        {
                            // Special case: Ensure that the type is not an anonymous type.
                            if (type.IsAnonymousType == false)
                            {
                                // Special case: Ensure that it's not a 'new' expression.
                                if (variableDeclaration.Variables.First().Initializer.Value.IsKind(SyntaxKind.ObjectCreationExpression))
                                {
                                    result = false;
                                }
                                else
                                {
                                    result = true;
                                }
                            }
                            else
                            {
                                result = false;
                            }
                        }
                        else
                        {
                            result = false;
                        }
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    result = false;
                }
            }
            else
            {
                result = false;
            }

            return result;
        }
开发者ID:0x084E,项目名称:VarUsageAnalyzer,代码行数:60,代码来源:VarDiagnosticAnalyzer.cs

示例2: VisitVariableDeclaration

    public override void VisitVariableDeclaration(VariableDeclarationSyntax node)
    {
      // start with variable type
      if (node.Type.IsVar)
      {
        // no idea
        cb.AppendWithIndent("auto ");
      }
      else
      {
        var si = model.GetSymbolInfo(node.Type);
        ITypeSymbol ts = (ITypeSymbol) si.Symbol;
        cb.AppendWithIndent(ts.ToCppType()).Append(" ");
      }

      // now comes the name(s)
      for (int i = 0; i < node.Variables.Count; ++i)
      {
        var v = node.Variables[i];
        cb.Append(v.Identifier.Text);
        if (v.Initializer != null)
        {
          cb.Append(" = ");
          v.Initializer.Accept(this);
        }

        cb.AppendLine(i + 1 == node.Variables.Count ? ";" : ",");
      }
    }
开发者ID:codedecay,项目名称:Blackmire,代码行数:29,代码来源:CppImplWalker.cs

示例3: VariableDeclaration

        public static string VariableDeclaration(VariableDeclarationSyntax declaration)
        {
            var isConst = declaration.Parent is LocalDeclarationStatementSyntax
                          && ((LocalDeclarationStatementSyntax) declaration.Parent).IsConst;

            var output = isConst ? "let " :  "var ";

            foreach (var currVar in declaration.Variables)
            {
                output += currVar.Identifier.Text;

                if (!declaration.Type.IsVar)
                {
                    output += ": " + SyntaxNode(declaration.Type);
                }

                if (currVar.Initializer != null)
                {
                    output += " " + SyntaxNode(currVar.Initializer);
                }
                output += ", ";
            }

            return output.TrimEnd(',', ' ');
        }
开发者ID:UIKit0,项目名称:SharpSwift,代码行数:25,代码来源:DeclarationSyntaxParser.cs

示例4: IsTypeApparentInDeclaration

 /// <summary>
 /// Returns true if type information could be gleaned by simply looking at the given statement.
 /// This typically means that the type name occurs in right hand side of an assignment.
 /// </summary>
 private bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, TypeStylePreference stylePreferences, CancellationToken cancellationToken)
 {
     var initializer = variableDeclaration.Variables.Single().Initializer;
     var initializerExpression = GetInitializerExpression(initializer);
     var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type;
     return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel,cancellationToken, declaredTypeSymbol);
 }
开发者ID:jkotas,项目名称:roslyn,代码行数:11,代码来源:CSharpTypeStyleDiagnosticAnalyzerBase.State.cs

示例5: Go

        public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration)
        {
            foreach (var variable in declaration.Variables)
            {
                ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable);

                var isRef = false; //UsedAsRef(variable, symbol);

                writer.WriteIndent();
                // writer.Write("var ");

                //                if (isRef) //Not needed c++ can passby ref
                //                {
                //
                //                    var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type);
                //
                //                    var localSymbol = symbol as ILocalSymbol;
                //                    var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : "";
                //                                        writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >");
                //                    writer.Write("" + typeStr + ptr + "");
                //
                //                    writer.Write(" ");
                //                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                //                    
                //                    Program.RefOutSymbols.TryAdd(symbol, null);
                //
                //                    writer.Write(" = std::make_shared < ");
                //                    writer.Write(typeStr + ptr);
                //                    writer.Write(" >(");
                //
                //                    WriteInitializer(writer, declaration, variable);
                //
                //                    writer.Write(")");
                //                }
                //                else
                {
                    var lsymbol = symbol as ILocalSymbol;

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                    {
                        writer.Write(" ");
// Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
                    }

                    writer.Write(TypeProcessor.ConvertType(declaration.Type));

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                        writer.Write(" ");

                    writer.Write(" ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
开发者ID:mortezabarzkar,项目名称:SharpNative,代码行数:59,代码来源:WriteVariableDeclaration.cs

示例6: WithDeclaration

        public ArgumentSyntax WithDeclaration(VariableDeclarationSyntax declaration)
        {
            if (this.RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
            {
                throw new InvalidOperationException();
            }

            return this.WithExpressionOrDeclaration(declaration);
        }
开发者ID:vslsnap,项目名称:roslyn,代码行数:9,代码来源:ArgumentSyntax.cs

示例7: TryValidateLocalVariableType

        static bool TryValidateLocalVariableType(LocalDeclarationStatementSyntax localDeclarationStatementSyntax, VariableDeclarationSyntax variableDeclarationSyntax)
        {
            //Either we don't have a local variable or we're using constant value
            if (localDeclarationStatementSyntax == null ||
                localDeclarationStatementSyntax.IsConst ||
                localDeclarationStatementSyntax.ChildNodes().OfType<VariableDeclarationSyntax>().Count() != 1)
                return false;

            //We don't want to raise a diagnostic if the local variable is already a var
            return !variableDeclarationSyntax.Type.IsVar;
        }
开发者ID:pgrefviau,项目名称:RefactoringEssentials,代码行数:11,代码来源:SuggestUseVarKeywordEvidentAnalyzer.cs

示例8: RemoveHungarianPrefix

 private async Task<Solution> RemoveHungarianPrefix(Document document, VariableDeclarationSyntax token, CancellationToken cancellationToken)
 {
     var identifierToken = token.Variables.First();
     var newName = DehungarianAnalyzer.SuggestDehungarianName(identifierToken.Identifier.Text);
     var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     var tokenSymbol = semanticModel.GetDeclaredSymbol(token.Variables.First(), cancellationToken);
     var originalSolution = document.Project.Solution;
     var optionSet = originalSolution.Workspace.Options;
     var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, tokenSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);
     return newSolution;
 }
开发者ID:CaptiveAire,项目名称:dehungarian,代码行数:11,代码来源:CodeFixProvider.cs

示例9: ChangeToFunc

        private async Task<Document> ChangeToFunc(Document document, VariableDeclarationSyntax variableDeclaration, CancellationToken cancellationToken)
        {
            // Change the variable declaration
            var newDeclaration = variableDeclaration.WithType(SyntaxFactory.ParseTypeName("System.Func<System.Threading.Tasks.Task>").WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation)
                .WithLeadingTrivia(variableDeclaration.Type.GetLeadingTrivia()).WithTrailingTrivia(variableDeclaration.Type.GetTrailingTrivia()));

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var newRoot = oldRoot.ReplaceNode(variableDeclaration, newDeclaration);
            var newDocument = document.WithSyntaxRoot(newRoot);

            // Return document with transformed tree.
            return newDocument;
        }
开发者ID:jerriclynsjohn,项目名称:roslyn,代码行数:13,代码来源:AsyncLambdaVariableCodeFix.cs

示例10: MakeStaticDeclarationImplicit

        private async Task<Document> MakeStaticDeclarationImplicit(Document document,
            VariableDeclarationSyntax variableDeclaration, CancellationToken
                cancellationToken)
        {
            var newVariableDeclaration = variableDeclaration.WithType(SyntaxFactory.IdentifierName("var"));

            newVariableDeclaration = newVariableDeclaration.WithAdditionalAnnotations(Formatter.Annotation);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = oldRoot.ReplaceNode(variableDeclaration, newVariableDeclaration);

            return document.WithSyntaxRoot(newRoot);

        }
开发者ID:TheDutchDevil,项目名称:Halcyon,代码行数:14,代码来源:TypeToVarFixProvider.cs

示例11: VariableDeclarationTranslation

        public VariableDeclarationTranslation(VariableDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
        {
            Type = syntax.Type.Get<TypeTranslation>(this);
            Variables = syntax.Variables.Get<VariableDeclaratorSyntax, VariableDeclaratorTranslation>(this);
            if (!syntax.Type.IsVar)
            {
                Variables.GetEnumerable().First().FirstType = Type;
            }

            foreach (var item in Variables.GetEnumerable())
            {
                item.KnownType = Type;
            }
        }
开发者ID:asthomas,项目名称:TypescriptSyntaxPaste,代码行数:14,代码来源:VariableDeclarationTranslation.cs

示例12: UseVarAsync

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

            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var localDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
            var variableDeclaration = localDeclaration.Declaration;
            var numVariables = variableDeclaration.Variables.Count;

            var newVariableDeclarations = new VariableDeclarationSyntax[numVariables];

            var varSyntax = SyntaxFactory.IdentifierName("var");

            //Create a new var declaration for each variable.
            for (var i = 0; i < numVariables; i++)
            {
                var originalVariable = variableDeclaration.Variables[i];
                var newLeadingTrivia = originalVariable.GetLeadingTrivia();

                //Get the trivia from the separator as well
                if (i != 0)
                {
                    newLeadingTrivia = newLeadingTrivia.InsertRange(0,
                        variableDeclaration.Variables.GetSeparator(i-1).GetAllTrivia());
                }

                newVariableDeclarations[i] = SyntaxFactory.VariableDeclaration(varSyntax)
                    .AddVariables(originalVariable.WithLeadingTrivia(newLeadingTrivia));
            }

            //ensure trivia for leading type node is preserved
            var originalTypeSyntax = variableDeclaration.Type;
            newVariableDeclarations[0] = newVariableDeclarations[0]
                .WithType((TypeSyntax) varSyntax.WithSameTriviaAs(originalTypeSyntax));

            var newLocalDeclarationStatements = newVariableDeclarations.Select(SyntaxFactory.LocalDeclarationStatement).ToList();


            //Preserve the trivia for the entire statement at the start and at the end
            newLocalDeclarationStatements[0] =
                newLocalDeclarationStatements[0].WithLeadingTrivia(variableDeclaration.GetLeadingTrivia());
            var lastIndex = numVariables -1;
            newLocalDeclarationStatements[lastIndex] =
                newLocalDeclarationStatements[lastIndex].WithTrailingTrivia(localDeclaration.GetTrailingTrivia());

            var newRoot = root.ReplaceNode(localDeclaration, newLocalDeclarationStatements);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
开发者ID:rfiori,项目名称:code-cracker,代码行数:49,代码来源:AlwaysUseVarCodeFixProvider.cs

示例13: ForStatement

 /// <summary>Creates a new ForStatementSyntax instance.</summary>
 public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return ForStatement(
         forKeyword: forKeyword,
         openParenToken: openParenToken,
         refKeyword: default(SyntaxToken),
         deconstruction: null,
         declaration: declaration,
         initializers: initializers,
         firstSemicolonToken: firstSemicolonToken,
         condition: condition,
         secondSemicolonToken: secondSemicolonToken,
         incrementors: incrementors,
         closeParenToken: closeParenToken,
         statement: statement);
 }
开发者ID:Shiney,项目名称:roslyn,代码行数:17,代码来源:ForStatementSyntax.cs

示例14: MakeLocalVariableList

        private void MakeLocalVariableList(VariableDeclarationSyntax syntax)
        {
            int count = 0;
            foreach (var v in syntax.Variables)
            {
                if (count == 0)
                {
                    _output.Write(v.Identifier, v.Identifier.ValueText);
                }
                else
                {
                    _output.TrivialWrite(", ");
                    _output.Write(v.Identifier, v.Identifier.ValueText);
                }

                if (v.Initializer != null)
                {
                    _output.TrivialWrite(" = ");
                    this.Visit(v.Initializer);
                }
                count++;
            }
        }
开发者ID:rexzh,项目名称:SharpJs,代码行数:23,代码来源:Rewriter_Misc.cs

示例15: BindForOrUsingOrFixedDeclarations

        internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, DiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations)
        {
            if (nodeOpt == null)
            {
                declarations = ImmutableArray<BoundLocalDeclaration>.Empty;
                return null;
            }

            var typeSyntax = nodeOpt.Type;

            AliasSymbol alias;
            bool isVar;
            TypeSymbol declType = BindType(typeSyntax, diagnostics, out isVar, out alias);

            Debug.Assert((object)declType != null || isVar);

            var variables = nodeOpt.Variables;
            int count = variables.Count;
            Debug.Assert(count > 0);

            if (isVar && count > 1)
            {
                // There are a number of ways in which a var decl can be illegal, but in these 
                // cases we should report an error and then keep right on going with the inference.

                Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt);
            }

            var declarationArray = new BoundLocalDeclaration[count];

            for (int i = 0; i < count; i++)
            {
                var variableDeclarator = variables[i];
                var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics);

                declarationArray[i] = declaration;
            }

            declarations = declarationArray.AsImmutableOrNull();

            return (count == 1) ?
                (BoundStatement)declarations[0] :
                new BoundMultipleLocalDeclarations(nodeOpt, declarations);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:44,代码来源:Binder_Statements.cs


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