-->

Can’t assign delegate an anonymous method with les

2020-03-23 17:33发布

问题:

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);
    }
}

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

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?

回答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.)

EDIT: 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 :)