无法分配到较少的特定参数类型的委托匿名方法 [英] Can’t assign to delegate an anonymous method with less specific parameter type

查看:86
本文介绍了无法分配到较少的特定参数类型的委托匿名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够分配方法 M 委托对象 D 一个没有特定的参数类型,但当我想用同样的分配匿名方法的签名方法 M D ,我得到一个错误。

这是为什么?

 类derivedEventArgs:EventArgs的{}

委托无效newDelegate(对象o,derivedEventArgs E);

静态无效的主要(字串[] args)
{
    newDelegate D =米; // 好
                D =(对象o,EventArgs五)=> {}; // 错误
}

公共静态无效的M(对象o,EventArgs五){}
 

解决方案

贾里德当然是正确的,这是由设计。

原因:设计是,在逆变方式转换的情况下,你可能有你没有写一个方法,并把它分配给了你没有写任何一个委托变量。你不控制的类型。所以我们去了一下简单的你,让参数匹配contravariantly和返回类型匹配协变。

在λ-到委托的转换,您的的控制被分配的东西。没有任何的从使它完全匹配的参数类型停止的你,因此,我们的需要的你。这里没有捏造允许的。

I’m able to assign a method M to delegate object d with a less specific parameter type, but when I want to assign an anonymous method with same the signature as method M to d, I get an error.

Why is that?

class derivedEventArgs : EventArgs { }

delegate void newDelegate(object o, derivedEventArgs e); 

static void Main(string[] args)
{
    newDelegate d = M; // ok
                d = (object o, EventArgs e) => { }; // error
}

public static void M(object o, EventArgs e) { }

解决方案

Jared is of course correct that this is by design.

The reason for that design is that in the contravariant method conversion case, you might have a method that you didn't write, and be assigning it to a delegate variable that you didn't write either. You don't control the types. So we go a bit easy on you and let the parameters match contravariantly and the return types match covariantly.

In the lambda-to-delegate conversion, you do control the thing being assigned. There is nothing stopping you from making it an exact match in the parameter types and therefore we require you to. No fudging allowed here.

这篇关于无法分配到较少的特定参数类型的委托匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆