在IronPython中,我似乎不能让一个来自委托作用域之外的变量在它的作用域内改变(甚至出现)。这与我在C#和Python中可以做的事情相反。
在C#中,我可以执行以下(人为设计的)示例:
public delegate bool Del(int index);
public static void Main() {
int total_count = 0;
Del d = delegate (int index) {
total_count += 3;
return true;
};
for (int i = 4; i < 6; i++) {
d.Invoke(i);
}
Console.WriteLine(total_count); // prints 6
}
我可以用Python做同样的事情:
total_count = 0
def delegate(index):
global total_count
total_count += 3
for x in range(4,6):
delegate(x)
print(total_count) # prints 6
但是影响C#调用的Python委托中的Python变量会崩溃:
public class Foo {
public delegate bool Del(int index);
public static int FooIt(Del the_delegate) {
int unrelated_count = 0;
for (int i = 4; i < 6; i++) {
the_delegate(i);
unrelated_count++;
}
return unrelated_count;
}
}
import Foo
total_count = 0
def delegate(index):
global total_count
total_count += 3 # "global name 'total_count' is not defined"
return True
unrelated_count = Foo.FooIt(Foo.Del(delegate))
print total_count
有没有一种方法可以在不改变任何C#的情况下在Python委托中增加total_count
?
发布于 2015-04-06 22:43:27
在委托之外的作用域中向IronPython添加额外的global
行可以使其正常工作。这一行在纯Python版本中不是必需的:
public class Foo{
public delegate bool Del(int index);
public static int FooIt(Del the_delegate){
int unrelated_count = 0;
for(int i = 4; i < 6; i++){
the_delegate(i);
unrelated_count++;
}
return unrelated_count;
}
}
import Foo
global total_count # Adding this line made it work.
total_count = 0
def delegate(index):
global total_count # You need to keep this line, too.
total_count += 3
return True
unrelated_count = Foo.FooIt(Foo.Del(delegate))
print total_count # prints 6
https://stackoverflow.com/questions/29084285
复制相似问题