本文整理汇总了C#中VariableDeclarationStatement类的典型用法代码示例。如果您正苦于以下问题:C# VariableDeclarationStatement类的具体用法?C# VariableDeclarationStatement怎么用?C# VariableDeclarationStatement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
VariableDeclarationStatement类属于命名空间,在下文中一共展示了VariableDeclarationStatement类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
});
}
开发者ID:selony,项目名称:scriptcs,代码行数:60,代码来源:MethodVisitor.cs
示例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;
}
开发者ID:yayanyang,项目名称:monodevelop,代码行数:34,代码来源:DeclareVariables.cs
示例3: VisitVariableDeclarationStatement
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) {
foreach (var varNode in variableDeclarationStatement.Variables) {
AddVariable(varNode, varNode.Name);
}
base.VisitVariableDeclarationStatement(variableDeclarationStatement);
}
开发者ID:ShuntaoChen,项目名称:SaltarelleCompiler,代码行数:7,代码来源:VariableGatherer.cs
示例4: HandleVisitorVariableDeclarationStatementVisited
void HandleVisitorVariableDeclarationStatementVisited (VariableDeclarationStatement node, InspectionData data)
{
foreach (var rule in policy.Rules) {
if (rule.CheckVariableDeclaration (node, data))
return;
}
}
开发者ID:yayanyang,项目名称:monodevelop,代码行数:7,代码来源:NamingInspector.cs
示例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);
}
}
开发者ID:hduregger,项目名称:monodevelop,代码行数:34,代码来源:ConvertForeachToFor.cs
示例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);
}
开发者ID:ningboliuwei,项目名称:NRefactory_Demo,代码行数:8,代码来源:FindRedundantTypeInLocalVariableDeclaration.cs
示例7: VisitVariableDeclarationStatement
public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
{
if ((variableDeclarationStatement.Modifiers & Modifiers.Const) == Modifiers.Const)
{
UnlockWith(variableDeclarationStatement);
}
return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
}
开发者ID:jonasswiatek,项目名称:strokes,代码行数:9,代码来源:ConstKeywordAchievement.cs
示例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);
}
开发者ID:vlad2135,项目名称:strokes,代码行数:10,代码来源:AnonymousObjectAchievement.cs
示例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);
}
开发者ID:reshadi2,项目名称:mcjs,代码行数:11,代码来源:JSIntrumentor.cs
示例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;
}
开发者ID:adisik,项目名称:simple-assembly-explorer,代码行数:11,代码来源:ForControlVariableNotModifiedIssue.cs
示例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)
);
}
开发者ID:yayanyang,项目名称:monodevelop,代码行数:53,代码来源:UseVarKeywordInspector.cs
示例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);
}
}
}
开发者ID:KAW0,项目名称:Alter-Native,代码行数:12,代码来源:VariableLookupVisitor.cs
示例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));
}
}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:52,代码来源:VariableDeclaredInWideScopeIssue.cs
示例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);
}
开发者ID:ningboliuwei,项目名称:NRefactory_Demo,代码行数:13,代码来源:FindRedundantTypeInLocalVariableDeclaration.cs
示例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);
});
}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:51,代码来源:IntroduceConstantAction.cs
示例16: MoveDeclarationAction
static CodeAction MoveDeclarationAction(RefactoringContext context, AstNode insertAnchor,
VariableDeclarationStatement declarationStatement, VariableInitializer initializer)
{
var type = declarationStatement.Type.Clone();
var name = initializer.Name;
return new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
script.InsertBefore(declarationStatement, new ExpressionStatement() {
Expression = new AssignmentExpression(new IdentifierExpression(name), initializer.Initializer.Clone())
});
script.Remove(declarationStatement);
script.InsertBefore(insertAnchor, new VariableDeclarationStatement(type, name, Expression.Null));
});
}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:14,代码来源:MoveToOuterScopeAction.cs
示例17: GetFixes
protected override IEnumerable<CodeAction> GetFixes(BaseSemanticModel context, Node env,
string variableName)
{
var containingStatement = env.ContainingStatement;
// we don't give a fix for these cases since the general fix may not work
// lambda in while/do-while/for condition
if (containingStatement is WhileStatement || containingStatement is DoWhileStatement ||
containingStatement is ForStatement)
yield break;
// lambda in for initializer/iterator
if (containingStatement.Parent is ForStatement &&
((ForStatement)containingStatement.Parent).EmbeddedStatement != containingStatement)
yield break;
Action<Script> action = script =>
{
var newName = LocalVariableNamePicker.PickSafeName(
containingStatement.GetParent<EntityDeclaration>(),
Enumerable.Range(1, 100).Select(i => variableName + i));
var variableDecl = new VariableDeclarationStatement(new SimpleType("var"), newName,
new IdentifierExpression(variableName));
if (containingStatement.Parent is BlockStatement || containingStatement.Parent is SwitchSection)
{
script.InsertBefore(containingStatement, variableDecl);
}
else
{
var offset = script.GetCurrentOffset(containingStatement.StartLocation);
script.InsertBefore(containingStatement, variableDecl);
script.InsertText(offset, "{");
script.InsertText(script.GetCurrentOffset(containingStatement.EndLocation), "}");
script.FormatText(containingStatement.Parent);
}
var textNodes = new List<AstNode>();
textNodes.Add(variableDecl.Variables.First().NameToken);
foreach (var reference in env.GetAllReferences())
{
var identifier = new IdentifierExpression(newName);
script.Replace(reference.AstNode, identifier);
textNodes.Add(identifier);
}
script.Link(textNodes.ToArray());
};
yield return new CodeAction(context.TranslateString("Copy to local variable"), action, env.AstNode);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:50,代码来源:AccessToModifiedClosureIssue.cs
示例18: MoveInitializerAction
static CodeAction MoveInitializerAction(RefactoringContext context, AstNode insertAnchor,
VariableDeclarationStatement declaration, VariableInitializer initializer)
{
var type = declaration.Type.Clone();
var name = initializer.Name;
return new CodeAction(context.TranslateString("Move initializer to outer scope"), script => {
if (declaration.Variables.Count != 1) {
var innerDeclaration = RemoveInitializer(declaration, initializer);
script.InsertBefore(declaration, innerDeclaration);
}
script.Remove(declaration);
var outerDeclaration = new VariableDeclarationStatement(type, name, initializer.Initializer.Clone());
script.InsertBefore(insertAnchor, outerDeclaration);
});
}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:15,代码来源:MoveToOuterScopeAction.cs
示例19: DeclareVariable
/// <summary>
/// Declares a variable in the smallest required scope.
/// </summary>
/// <param name="node">The root of the subtree being searched for the best insertion position</param>
/// <param name="type">The type of the new variable</param>
/// <param name="name">The name of the new variable</param>
/// <param name="allowPassIntoLoops">Whether the variable is allowed to be placed inside a loop</param>
public static VariableDeclarationStatement DeclareVariable(AstNode node, AstType type, string name, bool allowPassIntoLoops = true)
{
VariableDeclarationStatement result = null;
AstNode pos = FindInsertPos(node, name, allowPassIntoLoops);
if (pos != null) {
Match m = assignmentPattern.Match(pos);
if (m != null && m.Get<IdentifierExpression>("ident").Single().Identifier == name) {
result = new VariableDeclarationStatement(type, name, m.Get<Expression>("init").Single().Detach());
pos.ReplaceWith(result);
} else {
result = new VariableDeclarationStatement(type, name);
pos.Parent.InsertChildBefore(pos, result, BlockStatement.StatementRole);
}
}
return result;
}
开发者ID:petr-k,项目名称:ILSpy,代码行数:23,代码来源:DeclareVariableInSmallestScope.cs
示例20: GetActions
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var foreachStatement = GetForeachStatement(context);
if (foreachStatement == null) {
yield break;
}
yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script => {
var result = context.Resolve(foreachStatement.InExpression);
var countProperty = GetCountProperty(result.Type);
// TODO: use another variable name if 'i' is already in use
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 variableDeclarationStatement = new VariableDeclarationStatement(
foreachStatement.VariableType.Clone(),
foreachStatement.VariableName,
new IndexerExpression(foreachStatement.InExpression.Clone(), id3)
);
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 {
variableDeclarationStatement
}
};
if (foreachStatement.EmbeddedStatement is BlockStatement) {
variableDeclarationStatement.Remove();
var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
if (oldBlock.Statements.Any()) {
oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
} else {
oldBlock.Statements.Add(variableDeclarationStatement);
}
forStatement.EmbeddedStatement = oldBlock;
} else {
forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
}
script.Replace (foreachStatement, forStatement);
script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
});
}
开发者ID:adisik,项目名称:simple-assembly-explorer,代码行数:46,代码来源:ConvertForeachToForAction.cs
注:本文中的VariableDeclarationStatement类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论