• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
简单不先于复杂,而是在复杂之后
博客园    首页    新随笔    联系   管理    订阅  订阅
委托中使用变体

当向委托分配一个方法时,协变和逆变会提供用于使委托类型与方法签名匹配的灵活性。 协变允许方法具有的派生返回类型比委托中定义的更多。 逆变允许方法具有的派生参数类型比委托类型中的更少。

示例 1:协变


说明

本示例演示如何将委托与具有返回类型的方法一起使用,这些返回类型派生自委托签名中的返回类型。 由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:逆变


说明

本示例演示如何将委托与具有某个类型的参数的方法一起使用,这些参数是委托签名参数类型的基类型。 使用逆变,可以使用一个事件处理程序而不是多个单独的处理程序。 例如,可以创建接受EventArgs输入参数的事件处理程序,并将其与将MouseEventArgs类型作为参数发送的Button.MouseClick事件一起使用,也可以将其与发送KeyEventArgs 参数的TextBox.KeyDown事件一起使用。

// Event hander 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;

}

 

 

 

 

posted on 2013-03-31 20:13  sharpCode  阅读(328)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3