IronPython委托中的外部范围变量

时间:2015-03-16 18:27:27

标签: delegates scope ironpython

在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

1 个答案:

答案 0 :(得分:0)

在委托之外的范围内向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