當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。