编程语言
首页 > 编程语言> > c# – 无法为委托分配具有较少特定参数类型的匿名方法

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

作者:互联网

参见英文答案 > Can’t assign to delegate an anonymous method with less specific parameter type                                    3个

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

标签:c,net,delegates,c-2-0
来源: https://codeday.me/bug/20190515/1111075.html