gpt4 book ai didi

c# - 为什么 C# 的重载解析在 Func 和 Action 之间不起作用?

转载 作者:可可西里 更新时间:2023-11-01 08:28:15 26 4
gpt4 key购买 nike

<分区>

因此,一个相当常见的 IEnumerable 扩展方法,运行:

public static IEnumerable<T> Run<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
yield return item;
}
}

当我尝试将其用于例如 DbSet.Add 时:

invoice.Items.Run(db.InvoiceItems.Add);
// NB: Add method signature is
// public T Add(T item) { ... }

...编译器提示它有错误的返回类型,因为它需要一个 void 方法。因此,为 Run 添加一个重载,它采用 Func 而不是 Action:

public static IEnumerable<T> Run<T>(this IEnumerable<T> source, Func<T, T> action)
{
return source.Select(action).ToList().AsEnumerable();
}

现在编译器提示“调用在以下方法之间不明确...”

所以我的问题是,Run 方法的 Action 重载对方法组无效时怎么会导致歧义?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com