无法为委托分配具有较少特定参数类型的匿名方法

时间:2010-05-06 07:08:29

标签: c# .net delegates c#-2.0

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(请参阅注释),原因很简单,因为字符串继承自object。同样,为什么它抱怨匿名方法类型(参见注释//案例4 :)

  

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

在正常方法的情况下,它没有?或者我将苹果与橙子进行比较? 另一种情况是为什么它接受没有参数的匿名方法?

1 个答案:

答案 0 :(得分:7)

方法组转换支持方差(从C#2开始 - 它们不在C#1中),匿名函数转换根本不支持。鉴于无论何时编写匿名函数,都可以编写适当的参数,为什么不这样做呢?据我所知,在那里允许差异没有任何好处,这将使规则更难以正确。 (方差最终在规范中相当复杂。)

编辑:没有参数列表的匿名方法基本上与任何委托的参数列表兼容,只要它没有out个参数即可。基本上它是一种说法,“我不关心参数。”这是lambda表达式没有的匿名方法的一个特性:)