本文整理汇总了C#中VariableDeclarationStatement类的典型用法代码示例。如果您正苦于以下问题:C# VariableDeclarationStatement类的具体用法?C# VariableDeclarationStatement怎么用?C# VariableDeclarationStatement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
VariableDeclarationStatement类属于命名空间,在下文中一共展示了VariableDeclarationStatement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
Guard.AgainstNullArgument("methodDeclaration", methodDeclaration);
IEnumerable<ParameterDeclaration> parameters = methodDeclaration
.GetChildrenByRole(Roles.Parameter)
.Select(x => (ParameterDeclaration)x.Clone());
var isVoid = false;
var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async);
AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone();
var type = returnType as PrimitiveType;
if (type != null)
{
isVoid = string.Compare(
type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0;
}
var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func"));
IEnumerable<AstType> types = parameters.Select(
x => x.GetChildByRole(Roles.Type).Clone());
methodType
.TypeArguments
.AddRange(types);
if (!isVoid)
{
methodType.TypeArguments.Add(returnType);
}
var methodName = GetIdentifierName(methodDeclaration);
var methodBody = methodDeclaration
.GetChildrenByRole(Roles.Body)
.FirstOrDefault();
if (methodBody == null)
{
throw new NullReferenceException(string.Format("Method '{0}' has no method body", methodName));
}
methodBody = (BlockStatement)methodBody.Clone();
var prototype = new VariableDeclarationStatement { Type = methodType };
prototype.Variables.Add(new VariableInitializer(methodName));
var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync };
var expression = new ExpressionStatement
{
Expression = new AssignmentExpression(
new IdentifierExpression(methodName),
anonymousMethod)
};
_methods.Add(new MethodVisitorResult
{
MethodDefinition = methodDeclaration,
MethodPrototype = prototype,
MethodExpression = expression
});
}
示例2: Run
public void Run(AstNode node)
{
Run(node, null);
// Declare all the variables at the end, after all the logic has run.
// This is done so that definite assignment analysis can work on a single representation and doesn't have to be updated
// when we change the AST.
foreach (var v in variablesToDeclare) {
if (v.ReplacedAssignment == null) {
BlockStatement block = (BlockStatement)v.InsertionPoint.Parent;
block.Statements.InsertBefore(
v.InsertionPoint,
new VariableDeclarationStatement((AstType)v.Type.Clone(), v.Name));
}
}
// First do all the insertions, then do all the replacements. This is necessary because a replacement might remove our reference point from the AST.
foreach (var v in variablesToDeclare) {
if (v.ReplacedAssignment != null) {
// We clone the right expression so that it doesn't get removed from the old ExpressionStatement,
// which might be still in use by the definite assignment graph.
VariableDeclarationStatement varDecl = new VariableDeclarationStatement {
Type = (AstType)v.Type.Clone(),
Variables = { new VariableInitializer(v.Name, v.ReplacedAssignment.Right.Detach()).CopyAnnotationsFrom(v.ReplacedAssignment) }
};
ExpressionStatement es = v.ReplacedAssignment.Parent as ExpressionStatement;
if (es != null) {
// Note: if this crashes with 'Cannot replace the root node', check whether two variables were assigned the same name
es.ReplaceWith(varDecl.CopyAnnotationsFrom(es));
} else {
v.ReplacedAssignment.ReplaceWith(varDecl);
}
}
}
variablesToDeclare = null;
}
示例3: VisitVariableDeclarationStatement
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) {
foreach (var varNode in variableDeclarationStatement.Variables) {
AddVariable(varNode, varNode.Name);
}
base.VisitVariableDeclarationStatement(variableDeclarationStatement);
}
示例4: HandleVisitorVariableDeclarationStatementVisited
void HandleVisitorVariableDeclarationStatementVisited (VariableDeclarationStatement node, InspectionData data)
{
foreach (var rule in policy.Rules) {
if (rule.CheckVariableDeclaration (node, data))
return;
}
}
示例5: Run
public void Run (RefactoringContext context)
{
var foreachStatement = GetForeachStatement (context);
var result = context.ResolveType (foreachStatement.InExpression);
var countProperty = GetCountProperty (result);
var initializer = new VariableDeclarationStatement (new PrimitiveType ("int"), "i", new PrimitiveExpression (0));
var id1 = new IdentifierExpression ("i");
var id2 = id1.Clone ();
var id3 = id1.Clone ();
var forStatement = new ForStatement () {
Initializers = { initializer },
Condition = new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (foreachStatement.InExpression.Clone (), countProperty)),
Iterators = { new ExpressionStatement (new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2)) },
EmbeddedStatement = new BlockStatement {
new VariableDeclarationStatement (foreachStatement.VariableType.Clone (), foreachStatement.VariableName, new IndexerExpression (foreachStatement.InExpression.Clone (), id3))
}
};
if (foreachStatement.EmbeddedStatement is BlockStatement) {
foreach (var child in ((BlockStatement)foreachStatement.EmbeddedStatement).Statements) {
forStatement.EmbeddedStatement.AddChild (child.Clone (), BlockStatement.StatementRole);
}
} else {
forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
}
using (var script = context.StartScript ()) {
script.Replace (foreachStatement, forStatement);
script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
}
}
示例6: VisitVariableDeclarationStatement
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement varDecl)
{
// if (CanBeSimplified(varDecl)) {
// varDecl.Type = new SimpleType("var");
// }
// recurse into the statement (there might be a lambda with additional variable declaration statements inside there)
base.VisitVariableDeclarationStatement(varDecl);
}
示例7: VisitVariableDeclarationStatement
public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
{
if ((variableDeclarationStatement.Modifiers & Modifiers.Const) == Modifiers.Const)
{
UnlockWith(variableDeclarationStatement);
}
return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
}
示例8: VisitVariableDeclarationStatement
public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
{
var anonInitializer = variableDeclarationStatement.Variables.FirstOrDefault(a => a.Initializer is AnonymousTypeCreateExpression);
if (anonInitializer != null)
{
UnlockWith(anonInitializer.Initializer);
}
return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
}
示例9: Visit
public override void Visit(VariableDeclarationStatement expression)
{
if (expression.Expression != null)
{
outStream.Write("var {0} = {1}(", expression.Identifier, printFuncName);
expression.Expression.Accept(this);
outStream.Write(", \"{0}\")", TempName);
}
else
outStream.Write("var {0}", expression.Identifier);
}
示例10: GetControlVariable
static VariableInitializer GetControlVariable(VariableDeclarationStatement variableDecl,
UnaryOperatorExpression condition)
{
var controlVariables = variableDecl.Variables.Where (
v =>
{
var identifier = new IdentifierExpression (v.Name);
return condition.Expression.Match (identifier).Success;
}).ToList ();
return controlVariables.Count == 1 ? controlVariables [0] : null;
}
示例11: HandleVisitiorVariableDeclarationStatementVisited
void HandleVisitiorVariableDeclarationStatementVisited (VariableDeclarationStatement node, InspectionData data)
{
if (node.Type is PrimitiveType)
return;
if (node.Type is SimpleType && ((SimpleType)node.Type).Identifier == "var")
return;
var severity = base.node.GetSeverity ();
if (severity == MonoDevelop.SourceEditor.QuickTaskSeverity.None)
return;
//only checks for cases where the type would be obvious - assignment of new, cast, etc.
//also check the type actually matches else the user might want to assign different subclasses later
foreach (var v in node.Variables) {
if (v.Initializer.IsNull)
return;
var arrCreate = v.Initializer as ArrayCreateExpression;
if (arrCreate != null) {
var n = node.Type as ComposedType;
//FIXME: check the specifier compatibility
if (n != null && n.ArraySpecifiers.Any () && n.BaseType.IsMatch (arrCreate.Type))
continue;
return;
}
var objCreate = v.Initializer as ObjectCreateExpression;
if (objCreate != null) {
if (objCreate.Type.IsMatch (node.Type))
continue;
return;
}
var asCast = v.Initializer as AsExpression;
if (asCast != null) {
if (asCast.Type.IsMatch (node.Type))
continue;
return;
}
var cast = v.Initializer as CastExpression;
if (cast != null) {
if (cast.Type.IsMatch (node.Type))
continue;
return;
}
return;
}
data.Add (new Result (
new DomRegion (node.Type.StartLocation.Line, node.Type.StartLocation.Column, node.Type.EndLocation.Line, node.Type.EndLocation.Column),
GettextCatalog.GetString ("Use implicitly typed local variable decaration"),
severity,
ResultCertainty.High,
ResultImportance.Medium,
severity != MonoDevelop.SourceEditor.QuickTaskSeverity.Suggestion)
);
}
示例12: VisitVariableDeclarationStatement
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
{
base.VisitVariableDeclarationStatement(variableDeclarationStatement);
foreach (var varDecl in variableDeclarationStatement.Variables) {
if (startLocation.IsEmpty || startLocation <= varDecl.StartLocation && varDecl.EndLocation <= endLocation) {
var result = context.Resolve(varDecl);
var local = result as LocalResolveResult;
if (local != null && !UsedVariables.Contains(local.Variable))
UsedVariables.Add(local.Variable);
}
}
}
示例13: VisitVariableDeclarationStatement
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
{
base.VisitVariableDeclarationStatement(variableDeclarationStatement);
if (!(variableDeclarationStatement.Parent is BlockStatement))
// We are somewhere weird, like a the ResourceAquisition of a using statement
return;
if (variableDeclarationStatement.Variables.Count > 1)
return;
// Start at the parent node. Presumably this is a BlockStatement
var rootNode = variableDeclarationStatement.Parent;
var variableInitializer = variableDeclarationStatement.Variables.First();
var identifiers = GetIdentifiers(rootNode.Descendants, variableInitializer.Name).ToList();
if (identifiers.Count == 0)
// variable is not used
return;
AstNode deepestCommonAncestor = GetDeepestCommonAncestor(rootNode, identifiers);
var path = GetPath(rootNode, deepestCommonAncestor);
// Restrict path to only those where the initializer has not changed
var firstInitializerChange = GetFirstInitializerChange(variableDeclarationStatement, path, variableInitializer.Initializer);
if (firstInitializerChange != null) {
path = GetPath(rootNode, firstInitializerChange);
}
// Restict to locations outside of blacklisted node types
var firstBlackListedNode = (from node in path
where moveTargetBlacklist.Contains(node.GetType())
select node).FirstOrDefault();
if (firstBlackListedNode != null) {
path = GetPath(rootNode, firstBlackListedNode);
}
// Get the most nested possible target for the move
Statement mostNestedFollowingStatement = null;
for (int i = path.Count - 1; i >= 0; i--) {
var statement = path[i] as Statement;
if (statement != null && (IsScopeContainer(statement.Parent) || IsScopeContainer(statement))) {
mostNestedFollowingStatement = statement;
break;
}
}
if (mostNestedFollowingStatement != null && mostNestedFollowingStatement != rootNode && mostNestedFollowingStatement.Parent != rootNode) {
AddIssue(variableDeclarationStatement, context.TranslateString("Variable could be moved to a nested scope"),
GetActions(variableDeclarationStatement, mostNestedFollowingStatement));
}
}
示例14: CanBeSimplified
bool CanBeSimplified(VariableDeclarationStatement varDecl)
{
if (varDecl.Variables.Count != 1)
return false;
if (varDecl.Modifiers != Modifiers.None) // this line was "forgotten" in the article
return false;
VariableInitializer v = varDecl.Variables.Single();
ObjectCreateExpression oce = v.Initializer as ObjectCreateExpression;
if (oce == null)
return false;
//return ?AreEqualTypes?(varDecl.Type, oce.Type);
return varDecl.Type.IsMatch(oce.Type);
}
示例15: GetActions
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null)
yield break;
var statement = context.GetNode<Statement>();
if (statement == null) {
yield break;
}
var resolveResult = context.Resolve(pexpr);
yield return new CodeAction(context.TranslateString("Create local constant"), script => {
string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
if (service != null)
name = service.CheckName(context, name, AffectedEntity.LocalConstant);
var initializer = new VariableInitializer(name, pexpr.Clone());
var decl = new VariableDeclarationStatement() {
Type = context.CreateShortType(resolveResult.Type),
Modifiers = Modifiers.Const,
Variables = { initializer }
};
script.InsertBefore(statement, decl);
var variableUsage = new IdentifierExpression(name);
script.Replace(pexpr, variableUsage);
script.Link(initializer.NameToken, variableUsage);
});
yield return new CodeAction(context.TranslateString("Create constant field"), script => {
string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
if (service != null)
name = service.CheckName(context, name, AffectedEntity.ConstantField);
var initializer = new VariableInitializer(name, pexpr.Clone());
var decl = new FieldDeclaration() {
ReturnType = context.CreateShortType(resolveResult.Type),
Modifiers = Modifiers.Const,
Variables = { initializer }
};
var variableUsage = new IdentifierExpression(name);
script.Replace(pexpr, variableUsage);
// script.Link(initializer.NameToken, variableUsage);
script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
});
}