gpt4 book ai didi

c# - 无法为参数类型不太具体的匿名方法分配委托(delegate)

转载 作者:太空狗 更新时间:2023-10-29 23:04:12 26 4
gpt4 key购买 nike

<分区>

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

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com