加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#类型推断失败,包含默认参数的方法

发布时间:2020-12-15 04:31:23 所属栏目:百科 来源:网络整理
导读:说我有以下方法: static int MethodWithDefaultParameters(int a,int b=0,int c=1){ return a + b + c;} 然后我在LINQ查询中使用此方法,如下所示: Enumerable.Range(1,10).Select(MethodWithDefaultParameters); 这失败了: Error 1 The type arguments fo
说我有以下方法:
static int MethodWithDefaultParameters(int a,int b=0,int c=1)
{
    return a + b + c;
}

然后我在LINQ查询中使用此方法,如下所示:

Enumerable.Range(1,10).Select(MethodWithDefaultParameters);

这失败了:

Error 1 The type arguments for method ‘System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.

当然,我可以通过插入一个转发函数调用的lambda来解决这个问题:

Enumerable.Range(1,10).Select(i => MethodWithDefaultParameters(i));

但我的问题是为什么类型推断失败了?据我所知,它不应该是模糊的,因为只有一个函数变量满足输入变量.

解决方法

Select()有两个重载.将第二个参数(即代理)作为Func< TSource,TResult>以及采用Func< TSource,int,TResult>的一个参数.即具有一个参数或两个参数的方法签名.

你的方法既不满足.即使使用默认值,它仍然有三个参数.默认参数是编译时构造,必须在调用站点提供.它们不会在运行时通过调用委托实例来填充.

因此,事实上,您的解决方案是解决问题的两种合理方法之一.另一种方法是以不同方式实现默认参数(即“old-school”:)):

static int MethodWithDefaultParameters(int a)
{
    return MethodWithDefaultParameters(a,1);
}

static int MethodWithDefaultParameters(int a,int b,int c)
{
    return a + b + c;
}

然后,您可以直接调用Select()来使用MethodWithDefaultParameters,因为编译器将找到与Select()重载之一兼容的单参数重载.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读