使用委托中的变体 (C#)

将方法分配给委托时, 协变逆变 为使用方法签名匹配委托类型提供了灵活性。 协变允许方法具有的派生返回类型多于委托中定义的类型。 逆变允许方法具有的派生参数类型少于委托类型中的类型。

示例 1:协变

DESCRIPTION

本示例演示如何将委托与具有返回类型的方法一起使用,这些返回类型派生自委托签名中的返回类型。 返回的 DogsHandler 数据类型是 Dogs,该类型派生自委托中定义的 Mammals 类型。

代码

class Mammals {}  
class Dogs : Mammals {}  
  
class Program  
{  
    // Define the delegate.  
    public delegate Mammals HandlerMethod();  
  
    public static Mammals MammalsHandler()  
    {  
        return null;  
    }  
  
    public static Dogs DogsHandler()  
    {  
        return null;  
    }  
  
    static void Test()  
    {  
        HandlerMethod handlerMammals = MammalsHandler;  
  
        // Covariance enables this assignment.  
        HandlerMethod handlerDogs = DogsHandler;  
    }  
}  

示例 2:逆变

DESCRIPTION

本示例演示如何将委托与具有参数的方法一起使用,这些参数的类型是委托签名参数类型的基类型。 通过逆变可以使用一个事件处理程序而不是多个单独的处理程序。 下面的示例使用两个委托:

  • 定义 KeyEventHandler 事件签名的 委托。 其签名为:

    public delegate void KeyEventHandler(object sender, KeyEventArgs e)
    
  • 定义 MouseEventHandler 事件签名的 委托。 其签名为:

    public delegate void MouseEventHandler(object sender, MouseEventArgs e)
    

该示例使用参数定义事件处理程序 EventArgs ,并使用它来处理 Button.KeyDownButton.MouseClick 事件。 它可以实现这一点,因为EventArgsKeyEventArgsMouseEventArgs的基本类型。

代码

// Event handler that accepts a parameter of the EventArgs type.  
private void MultiHandler(object sender, System.EventArgs e)  
{  
    label1.Text = System.DateTime.Now.ToString();  
}  
  
public Form1()  
{  
    InitializeComponent();  
  
    // You can use a method that has an EventArgs parameter,  
    // although the event expects the KeyEventArgs parameter.  
    this.button1.KeyDown += this.MultiHandler;  
  
    // You can use the same method
    // for an event that expects the MouseEventArgs parameter.  
    this.button1.MouseClick += this.MultiHandler;  
  
}  

另请参阅