C# 方法没有重载匹配委托 Action ForEach

C# No overload for method matches delegate Action ForEach

我有一个我不太明白的难题,我很确定这只是我误解了什么。

我有以下扩展方法:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (var number in enumeration)
    {
        action?.Invoke(number);
    }
}

该扩展方法允许我执行以下操作:

var curiousNumbers = new List<BigInteger>();
// some code to fill curiousNumbers
curiousNumbers.ForEach(x => DebugLog(x));  

protected static void DebugLog(object logmessage)
{
    Logger.Log(logmessage.ToString());
}

然而,当我尝试执行此语法时:

curiousNumbers.ForEach(DebugLog);

我收到以下编译错误: 'BaseProblem.DebugLog(object)' 没有重载匹配委托 'Action<>BigInteger<>'

现在,如果我引入一个带有显式 BigInteger 类型的新 DebugLog 方法,一切都会编译并运行:

protected static void DebugLog(BigInteger logmessage)
{
    Logger.Log(logmessage.ToString());
}

这行得通,但是如果我有一个整数列表怎么办?我必须为每个显式类型添加另一个 DebugLog 方法。有没有一种方法可以重写 ForEach 扩展方法或 DebugLog 方法,它们都可以处理所有类型并允许使用 curiousNumbers.ForEach(DebugLog) 语法?

您遇到的编译错误是由于方法 DebugLog 具有类型 object 的参数,但您传递的序列包含类型 BigInteger 的元素。 ForEach<T> 的泛型类型 T 应该评估为哪种类型?两者不能同时存在。使 DebugLog 方法通用并解决您的问题:

protetected static void DebugLog<T>(T message)
{
    Logger.Log(message.ToString());
}

看看原型:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)

T 适用于可枚举的操作和输入,这就是为什么你有额外的约束。

由于您正在迭代 T 对象,因此您可能需要 运行 T 操作。

您的备选方案是:

1.Create 一个 T1,T2 ForEach:

public static void ForEach<T1,T2>(this IEnumerable<T1> enumeration, Action<T2> action)

2.Create DebugLog 的通用实现,而不是将对象作为参数传递。