ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 使用三元语句将扩展方法分配给委托

2019-07-03 21:56:18  阅读:301  来源: 互联网

标签:c methods extension-methods ternary


假设

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

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>类型的委托.我们可以使用:

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’

为什么会出现此错误?是否由于代表的性质是一种扩展方法;或者是由于short-hand 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,methods,extension-methods,ternary
来源: https://codeday.me/bug/20190703/1370653.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有