注释的地方为什么输入为: true ?
按我的理解 j 应该是个局部变量啊,请大侠解释下,谢谢!!
using System;namespace ConsoleApplication12
{
delegate bool D();
delegate bool D2(int i); class Test
{
D del;
D2 del2; public string Name
{
get;
private set;
} public void TestMethod(int input)
{
int j = 0; del = () =>
{
j = 10;
return j > input;
}; del2 = (x) =>
{
return x == j;
}; Console.WriteLine("j={0}", j); bool boolResult = del(); Console.WriteLine("j={0}.b={1}", j, boolResult);
} static void Main()
{
Test t = new Test();
t.TestMethod(5); t.Name = "name"; bool result = t.del2(10); Console.WriteLine(result); // 为什么是 true ?? }
}
}
按我的理解 j 应该是个局部变量啊,请大侠解释下,谢谢!!
using System;namespace ConsoleApplication12
{
delegate bool D();
delegate bool D2(int i); class Test
{
D del;
D2 del2; public string Name
{
get;
private set;
} public void TestMethod(int input)
{
int j = 0; del = () =>
{
j = 10;
return j > input;
}; del2 = (x) =>
{
return x == j;
}; Console.WriteLine("j={0}", j); bool boolResult = del(); Console.WriteLine("j={0}.b={1}", j, boolResult);
} static void Main()
{
Test t = new Test();
t.TestMethod(5); t.Name = "name"; bool result = t.del2(10); Console.WriteLine(result); // 为什么是 true ?? }
}
}
既然在TestMethod内部执行了“bool boolResult = del();”,那么j就等于10,你再执行
”(x) =>
{
return x == j;
};“
的话,x用10代入,那返回的不是相等吗?
bool boolResult = del(); j==10>5 为true
bool result = t.del2(10);这个的时候 参数==10 ==j 依然为true
相当于这个局部变量被提升为全局(全局这个词可能不当,但 j 的行为却很类似)的了????
可以把 bool boolResult = del(); 放到 main 里面,这个 j 的行为就更类似全局的了
http://topic.csdn.net/u/20090821/13/7c30e8cb-3d37-4d4f-9c11-0df1dd7be8f4.html?90036