gpt4 book ai didi

c# - 使用三元语句将扩展方法分配给委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 12:30:40 25 4
gpt4 key购买 nike

假设

假设我们有一个接口(interface),并且为该接口(interface)定义了以下扩展方法(它们的实现并不重要)

public interface IPerson;

public class IPersonExtensionMethods
{
public static bool SayHello(this IPerson talker, IPerson listener);
public static bool SayGoodbye(this IPerson talker, IPerson listener);
}

问题

我们知道这两种扩展方法在本质上是相同的,因为它们都接受 2 个类型为 IPerson 的参数。 , 并返回 bool .现在,假设我们要将 1 个扩展方法分配给类型为 Func<IPerson, IPerson, bool> 的委托(delegate)。我们可以使用:

Func<IPerson, IPerson, bool> whatShouldWeSay;
if (sayHello)
{
whatShouldWeSay = IPersonExtensionMethods.SayHello;
}
else
{
whatShouldWeSay = IPersonExtensionMethods.SayGoodbye;
}

但是,如果我们将 if语句简写如下:

Func<IPerson, IPerson, bool> whatShouldWeSay = (sayHello)
? IPersonExtensionMethods.SayHello
: IPersonExtensionMethods.SayGoodbye;

我们得到编译错误信息:

Type of conditional expression cannot be determined because there is no implicit conversion between 'method.group' and 'method.group'

问题

为什么会出现这个错误?是因为委托(delegate)的性质是扩展方法吗?还是因为简写if语句是确定结果类型的吗?还是完全不同?

最佳答案

错误的发生是因为在三元语句中,两个结果(true 和 false)需要是相同的类型。同样的事情也会发生在常规方法上,而不仅仅是扩展方法。您需要将它们转换为目标类型:

Func<IPerson, IPerson, bool> whatShouldWeSay = (sayHello) 
? (Func<IPerson, IPerson, bool>)IPersonExtensionMethods.SayHello
: (Func<IPerson, IPerson, bool>)IPersonExtensionMethods.SayGoodbye;

我在三元语句中使用 null 时遇到过这种情况,看到 null 被转换为某种可空类型感觉很奇怪。这可以在这里以更简单的方式显示:

// Doesn't compile
int? a = true ? 10 : null;

// Compiles
int? a = true ? 10 : (int?)null;

我们得到以下编译器错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

关于c# - 使用三元语句将扩展方法分配给委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680790/

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