无法使用 Func 推断类型参数

本文关键字:类型参数 Func | 更新日期: 2023-09-27 18:32:05

一位同事写了这个扩展方法,我想为它生成一个示例:

namespace ExtensionMethods {
    public static class MyExtensions {
        public static Res MyAggregate<T, Res>(this IEnumerable<T> source, Func<Res, int, T, Res> f) {
            var i = 0;
            Res result = default(Res);
            foreach (T x in source) {
                result = f(result, i, x);
                i++;
            }
            return result;
        }
    }
}

它创建一个泛型聚合方法,该方法还包括一个索引。

我的示例(如下)采用字符串列表,并连接第一个单词的第一个字母,第二个单词的第二个字母,依此类推。

namespace ExtensionMethods {
    public class Program {
        public static string OffsetChars(string x, int i, string y) {
            return x + y[i];
        }
        static void Main(string[] args) {
            List<string> test = new List<string>() { "hello", "there", "you" };
            // get h from (h)ello, h from t(h)ere and u from yo(u) (hhu)
            string result = test.MyAggregate<string, string>(OffsetChars);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

我的问题是关于这一行(重要的):

string result = test.MyAggregate<string, string>(OffsetChars);

如果没有<string, string>就会出现一个错误,即无法从使用情况中推断出参数的类型。我的问题:

为什么不能推断出来?我的代码中是否缺少一些可以推断它们的东西?

我使用显式委托进行了测试(如下所示),但发生了相同的错误:

namespace ExtensionMethods {
    delegate string OffsetMethod(string x, int i, string y);
    public class Program {
        public static string OffsetChars(string x, int i, string y) {
            return x + y[i];
        }
        static void Main(string[] args) {
            List<string> test = new List<string>() { "hello", "there", "you" };
            // get h from (h)ello, h from t(h)ere and u from yo(u) (hhu)
            OffsetMethod myMethod = OffsetChars;
            string result = test.MyAggregate(myMethod);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

总而言之,我想确保我的代码没有遗漏任何内容,并且假设我没有,以了解为什么无法推断参数类型。

无法使用 Func 推断类型参数

您的方法只是一个委托,因此没有任何可以推断的泛型类型参数。当您将OffsetChars定义为通用Func时,可以很好地推断出它们:

public static Func<string, int, string, string> OffsetChars = (x, i, y) =>
{
    return x + y[i];
};

> WERTZUI 是对的,因为委托没有任何泛型参数,编译器无法推断它,所以你有 se 错误。