Browse Source

Don't declare variables within anonymous methods if they are supposed to be declared outside.

pull/37/head
Daniel Grunwald 15 years ago
parent
commit
2d69b94494
  1. 10
      ICSharpCode.Decompiler/Ast/DeclareVariableInSmallestScope.cs
  2. 21
      ICSharpCode.Decompiler/Tests/DelegateConstruction.cs

10
ICSharpCode.Decompiler/Ast/DeclareVariableInSmallestScope.cs

@ -59,15 +59,19 @@ namespace Decompiler
} }
node = node.NextSibling; node = node.NextSibling;
} }
if (withinPos != null && withinPos.Role == BlockStatement.StatementRole && (allowPassIntoLoops || !IsLoop(pos))) if (withinPos != null && withinPos.Role == BlockStatement.StatementRole && AllowPassInto(pos, allowPassIntoLoops))
return withinPos; return withinPos;
else else
return pos; return pos;
} }
static bool IsLoop(AstNode node) static bool AllowPassInto(AstNode node, bool allowPassIntoLoops)
{ {
return node is ForStatement || node is ForeachStatement || node is DoWhileStatement || node is WhileStatement; if (node is AnonymousMethodExpression || node is LambdaExpression)
return false;
if (node is ForStatement || node is ForeachStatement || node is DoWhileStatement || node is WhileStatement)
return allowPassIntoLoops;
return true;
} }
} }
} }

21
ICSharpCode.Decompiler/Tests/DelegateConstruction.cs

@ -2,6 +2,7 @@
// This code is distributed under MIT X11 license (for details please see \doc\license.txt) // This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System; using System;
using System.Collections.Generic;
public static class DelegateConstruction public static class DelegateConstruction
{ {
@ -38,4 +39,24 @@ public static class DelegateConstruction
{ {
return new Func<string>(((string)null).ToUpper); return new Func<string>(((string)null).ToUpper);
} }
public static List<Action<int>> AnonymousMethodStoreWithinLoop()
{
List<Action<int>> list = new List<Action<int>>();
for (int i = 0; i < 10; i++) {
int counter;
list.Add(x => counter = x);
}
return list;
}
public static List<Action<int>> AnonymousMethodStoreOutsideLoop()
{
List<Action<int>> list = new List<Action<int>>();
int counter;
for (int i = 0; i < 10; i++) {
list.Add(x => counter = x);
}
return list;
}
} }

Loading…
Cancel
Save