将 Boo 方法添加到 C# 多播委托时出错
题
我正在开发一些需要由 C# 中的现有委托通知的 Boo 代码。我在构造函数中遇到 Boo 编译错误 ActionBoo
班级。请查看错误消息以及我尝试过的每个替代方案。
# Boo
import System
class ActionBoo:
def constructor():
# Alternative #1
# ActionBoo.boo(9,25): BCE0051: Operator '+' cannot be used with a left hand side of type 'System.Action' and a right hand side of type 'callable(int) as void'.
ActionCS.action += Boo
# Alternative #2
# ActionBoo.boo(13,25): BCE0051: Operator '+' cannot be used with a left hand side of type 'System.Action' and a right hand side of type 'System.Action'.
ActionCS.action += Action[of int](Boo)
# Alternative #3
# This works, but it resets the delegate already set up in C#
ActionCS.action = Boo
def Boo(boo as int):
print 'Boo: ' + boo
actioncs = ActionCS()
actionBoo = ActionBoo()
ActionCS.action(3)
ActionCS
是具有多播委托的现有 C# 代码。这是原始代码的简化版本:
// C#
using System;
public class ActionCS
{
public static Action<int> action;
public ActionCS()
{
action += Foo;
action += Bar;
}
public void Foo(int foo)
{
Console.WriteLine("Foo: " + foo);
}
public void Bar(int bar)
{
Console.WriteLine("Bar: " + bar);
}
public static void Main(string[] args)
{
ActionCS actioncs = new ActionCS();
action(5);
}
}
以下是我在 Linux 上使用 Mono (v2.10.9-0) 和 Boo (v0.9.4.9) 进行编译的方法:
$ mcs ActionCS.cs
$ mono booc.exe -r:ActionCS.exe ActionBoo.boo
C# 代码和 Boo 的“Alternative #3”通过调用以下命令可以正常运行:
$ mono ActionCS.exe
Foo: 5
Bar: 5
$ env MONO_PATH=$MONO_PATH:$BOO_HOME/bin mono ActionBoo.exe
Boo: 3
有谁知道如何修复 Boo 代码?
解决方案
在 C# 中 +=
只是语法糖 Delegate.Combine
, ,所以你可以用它来代替:
ActionCS.action = Delegate.Combine(ActionCS.action, Action[of int](Boo))
(请注意,我对 Boo 一无所知,只了解一般的 .NET,所以这只是一个有根据的猜测)
不隶属于 StackOverflow