IronPython 委托中的外部范围变量

Externally scoped variables in IronPython delegates

在 IronPython 中,我似乎无法从委托范围外获取变量以在其范围内更改(甚至出现)。这与我在 C# 和 Python.

中可以做的相反

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

public delegate bool Del(int index);

public static void Main() {
    int itemTally = 0;

    Del d = delegate (int index) {
        itemTally += 3;
        return true;
    };
        
    for (int i = 4; i < 6; i++) {
        d.Invoke(i);
    }

    Console.WriteLine(itemTally);  // prints 6
}

我可以在 Python 中做同样的事情:

item_tally = 0

def delegate(index):
    global item_tally
    item_tally += 3

for x in range(4, 6):
    delegate(x)

print(item_tally)  # prints 6

但是在 C# 调用的 Python 委托 中更改 Python 变量会崩溃:

public class BatchProcessor {
    public delegate bool Del(int index);

    public static int ProcessBatches(Del the_delegate) {
        int batchTally = 0;
        for (int i = 4; i < 6; i++) {
            the_delegate(i);
            batchTally++;
        }
        return batchTally;
    }
}
import BatchProcessor
item_tally = 0

def delegate(index):
    global item_tally
    item_tally += 3  # "global name 'total_count' is not defined"
    return True

batch_tally = BatchProcessor.ProcessBatches(BatchProcessor.Del(delegate))

print(item_tally)

有没有办法在不更改任何 C# 的情况下在 Python 委托中递增 total_count

在委托之外的范围内向 IronPython 添加额外的 global 行使其正常工作。该行在 Python-only 版本中不是必需的:

public class BatchProcessor {
    public delegate bool Del(int index);

    public static int ProcessBatches(Del the_delegate) {
        int batchTally = 0;
        for (int i = 4; i < 6; i++) {
            the_delegate(i);
            batchTally++;
        }
        return batchTally;
    }
}
import BatchProcessor
global item_tally  # Adding this line made it work.
item_tally = 0

def delegate(index):
    global item_tally  # You need to keep this line, too.
    item_tally += 3
    return True

batch_tally = BatchProcessor.ProcessBatches(BatchProcessor.Del(delegate))

print(item_tally)  # prints 6