有没有一种方法可以在C#中声明单播委托?例如。这样就不可能在单个时间点上由委托人引用多个方法。
我正在考虑一种在选择运行时使用哪种实现时实现灵活性的方法,但是要采取某种保护措施,以防止触发多个操作以避免任何副作用,尤其是对于非空返回类型委托。 / p>
答案 0 :(得分:1)
如果委托必须是一个事件。 (例如接口实现等)
您可以使用自定义事件访问器add/remove。 这仅在运行时有效,因此无法在编译时检测到。
这是一个例子:
private EventHandler _myHandler;
public event EventHandler MyHandler
{
add
{
if (_myHandler != null)
throw new InvalidOperationException("Only one eventhandler is supported");
_myHandler = value;
}
remove
{
// you might want to check if the delegate matches the current.
if (value == null || value == _myHandler)
_myHandler = null;
else
throw new InvalidOperationException("Unable to unregister, wrong eventhandler");
}
}
并将其用作正常事件:
MyHandler += (s, ee) => Console.WriteLine("MyHandler handler");
// if you're lazy, you could support deregistering with null
MyHandler -= null;
甚至可以使用Func<T>
代替EventHandler
答案 1 :(得分:0)
您需要封装委托的创建和分配。如果有多个处理程序,则可以引发异常。这是一个简单的例子
using System;
public delegate int MyDelegate(int x, int y);
public class Wrapper{
private MyDelegate d;
public Wrapper(){
this.d = null;
}
public void Assign(MyDelegate func){
if(d!= null && d.GetInvocationList().Length > 0){
throw new Exception("No more than 1 handlers allowed");
}
Console.WriteLine("Assigned");
this.d+= func;
}
}
public class Program
{
static int Sum(int x, int y)
{
return x + y;
}
static int Difference(int x, int y)
{
return x - y;
}
public static void Main()
{
Wrapper w = new Wrapper();
w.Assign(Sum);
w.Assign(Difference); //throws Exception;
}
}