gpt4 book ai didi

c# - 为什么编译器不能确定这个 lambda 是一个 Delegate?

转载 作者:太空狗 更新时间:2023-10-30 01:13:22 26 4
gpt4 key购买 nike

考虑这个小程序。

public class Program
{
public static void Main()
{
// the first path compiles
RunAction(() => { });

// the second path does not compile
RunDelegate(() => {});
}

private static void RunAction(Action run) => RunDelegate(run);
private static void RunDelegate(Delegate run) { }
}

第一个路径编译并暗示

  1. () => {} lambda 是一个Action
  2. Action 是一个Delegate,并且
  3. 因此 () => {} lambda 是一个Delegate

为什么第二条路径编译不通过?

通常,编译器能够在步骤 (1) 和 (3) 之间进行跳跃。下面是编译器通常如何处理这种嵌套 is-a 关系的示例。

public class Program2
{
public static void Main()
{
// both of these comple
AcceptPerson(new Programmer());
AcceptAnimal(new Programmer());
}

private static void AcceptPerson(Person p) => AcceptAnimal(p);
private static void AcceptAnimal(Animal a) { }
}

public class Programmer : Person { }
public class Person : Animal { }
public class Animal { }

最佳答案

匿名函数没有“默认”委托(delegate)类型,例如 () => { }。这样的表达式可以隐式转换为具有正确签名和返回类型的任何具体委托(delegate)类型(受各种自然变化规则的约束)。

您可以有许多匹配的委托(delegate)类型:

namespace TestFramework
{
public delegate void TestDelegate();
}

namespace System
{
public delegate void Action();
}

namespace System.Threading
{
public delegate void ThreadStart();
}

...

在所有这些可能的具体委托(delegate)类型中(每个都作为抽象 System.Delegate 作为其(间接)基类)没有首选。 p>

从表达式 () => { } 到它们每个都有一个隐式转换:

TestDelegate f = () => { };
Action g = () => { };
ThreadStart h = () => { };
...

由于隐式转换,您的调用 RunAction(() => { }); 有效。

但是对于 RunDelegate(() => {}); 并没有说明要使用什么具体的委托(delegate)类型。您必须执行以下操作之一:

RunDelegate((TestDelegate)(() => { }));
RunDelegate((Action)(() => { }));
RunDelegate((ThreadStart)(() => { }));
...

对您的问题的评论是正确的。

与此相关的是这将无法编译:

var f = () => { };  // illegal, shows that '() => { }' does NOT have type System.Action

你不能使用像 myBool 这样的子表达式吗? (() => { }) : null,依此类推。

关于c# - 为什么编译器不能确定这个 lambda 是一个 Delegate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380392/

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