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

前端之家收集整理的这篇文章主要介绍了C#类型推断失败,包含默认参数的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有以下方法
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()重载之一兼容的单参数重载.

原文链接:https://www.f2er.com/csharp/91324.html

猜你在找的C#相关文章