本文整理汇总了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;
}
示例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 ? ";" : ",");
}
}
示例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(',', ' ');
}
示例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);
}
示例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");
}
}
示例6: WithDeclaration
public ArgumentSyntax WithDeclaration(VariableDeclarationSyntax declaration)
{
if (this.RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
throw new InvalidOperationException();
}
return this.WithExpressionOrDeclaration(declaration);
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}
}
示例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;
}
示例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);
}
示例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++;
}
}
示例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);
}