方法的类型参数……无法从用法中推断出来。尝试明确指定类型参数

The type arguments for method … cannot be inferred from the usage. Try specifying the type arguments explicitly

我不确定,为什么调用 Map2 给了我

The type arguments for method 'Program.Map2(object, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

这是代码...

void Test()
{
    var test1 = Map1(1, MapIntToString);
    var test2 = Map2(1, MapIntToString);
}

To Map1<From, To>(From value, Func<From, To> mapFunc) => mapFunc(value);
To Map2<From, To>(object value, Func<From, To> mapFunc) => mapFunc((From)value);

string MapIntToString(int value) => Convert.ToString(value);

这是一个非常简单的例子。我需要将一些 DTO 列表转换为模型(并返回),但它应该是相同的情况...

露骨作品:

var test2 = Map2<int, string>(1, MapIntToString);

var test2 = Map2(1, (Func<int, string>)MapIntToString);

恐怕我无法指出为什么它不能隐式工作的原因。我个人的猜测是 MapIntToString 不是 不是 一个方法,而是一个可以毫无问题地转换为 Func<int, string> 的方法组(有一个成员),但该转换不用于解析泛型。

因为您已经定义了 object 类型的参数,而方法 MapIntToString 具有类型 int 的第一个参数。因此编译器无法确定传递给 mapFunc 的参数用于 Map2,即 object value 当前持有类型 int 的值。如果我们在 运行 时将其解析,那么您的代码将被翻译成如下所示,但首先它无法编译,因为它无法解析通用类型 From:

Map2<Object, String>(object value, Func<object, String> mapFunc) => mapFunc((object)value);

所以,显然这不会起作用,因为您的方法需要 int 类型的参数而不是 object.

在这种情况下,您需要明确说明类型参数,因为编译器不够智能,无法知道 object value 当前在其中保存类型 int 的值。