问题描述
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(见评论),好吧,原因很简单,因为字符串继承自对象.同样,为什么它抱怨匿名方法类型(参见注释//case 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 表达式所没有的匿名方法的一个特性:)
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 :)
这篇关于无法为具有较少特定参数类型的匿名方法分配委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!