首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >IronPython委托中的外部作用域变量

IronPython委托中的外部作用域变量
EN

Stack Overflow用户
提问于 2015-03-17 02:27:27
回答 1查看 107关注 0票数 0

在IronPython中,我似乎不能让一个来自委托作用域之外的变量在它的作用域内改变(甚至出现)。这与我在C#和Python中可以做的事情相反。

在C#中,我可以执行以下(人为设计的)示例:

代码语言:javascript
复制
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做同样的事情:

代码语言:javascript
复制
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变量会崩溃:

代码语言:javascript
复制
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;
    }
}
代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-06 22:43:27

在委托之外的作用域中向IronPython添加额外的global行可以使其正常工作。这一行在纯Python版本中不是必需的:

代码语言:javascript
复制
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;
    }
}
代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29084285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档