繁体   English   中英

如何在 C# 中声明单播委托

[英]How to declare a singlecast delegate in C#

有没有办法在 C# 中声明单播委托? 例如,在一个时间点不可能有多个方法被委托引用。

我正在考虑一种在选择在运行时使用的实现时实现灵活性的方法,但有某种保护措施可以防止触发多个操作以避免任何副作用,尤其是对于非 void 返回类型委托。

如果委托必须是事件。 (例如接口实现等)

您可以使用自定义事件访问器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

您需要封装委托创建和分配。 然后,如果有多个处理程序,您可以抛出异常。 这是一个简单的例子

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM