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

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

问题描述

public class Program
{
    delegate void Srini(string param);

    static void Main(string[] args)
    {
        Srini sr = new Srini(PrintHello1);
        sr += new Srini(PrintHello2);      //case 2:      
        sr += new Srini(delegate(string o) { Console.WriteLine(o); });
        sr += new Srini(delegate(object o) { Console.WriteLine(o.ToString()); }); //case 4:
        sr += new Srini(delegate { Console.WriteLine("This line is accepted,though the method signature is not Comp"); });//case 5
        sr("Hello World");
        Console.Read();
    }       

    static void PrintHello1(string  param)
    {
        Console.WriteLine(param);
    }

    static void PrintHello2(object param)
    {
        Console.WriteLine(param);
    }
}

编译器没有抱怨这种情况2(请参见注释),原因很简单,因为字符串是从对象继承的。同样,为什么它抱怨匿名方法类型(请参见注释//案例4 :)

Compiler doesn't complain about the case 2 (see the comment), well, the reason is straight forward since string inherits from object. Along the same lines, why is it complaining for anonymous method types (see the comment //case 4:) that


无法转换匿名方法委托类型'DelegateTest.Program.Srini',因为参数类型与委托参数类型不匹配

Cannot convert anonymous method to delegate type 'DelegateTest.Program.Srini' because the parameter types do not match the delegate parameter types

方法不是吗?还是我比较苹果和桔子?
另一种情况是为什么它接受不带参数的匿名方法?

where as in case of normal method it doesn't? Or am I comparing apples with oranges? Another case is why is it accepting anonymous method without parameters?

推荐答案

方法组转换支持方差(从C#开始) 2-它们不在C#1中),匿名函数转换根本就没有。假设只要您编写匿名函数,您就可以 编写适当的参数,为什么不这样做呢?据我所知,在那儿允许差异是没有好处的,这会使规则更难正确。 (差异最终在规范中变得非常复杂。)

Method group conversions support variance (as of C# 2 - they didn't in C# 1), anonymous function conversions simply don't. Given that whenever you write an anonymous function you can write the appropriate parameter, why not just do so? There would be no benefit in allowing variance there as far as I can see, and it would make the rules harder to get right. (Variance ends up being pretty complex in the spec.)

编辑:不带参数列表的匿名方法基本上可以与任何委托的参数列表兼容,只要它不兼容即可。没有 out 参数。基本上,这是一种表达方式,我不在乎参数。这是lambda表达式没有的匿名方法的 one 功能:)

An anonymous method without a parameter list is basically compatible with any delegate's parameter list so long as it doesn't have out parameters. Basically it's a way of saying, "I don't care about the parameters." It's the one feature of anonymous methods that lambda expressions don't have :)

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

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