【问题标题】:Type cannot be inferred within a generic delegate无法在泛型委托中推断类型
【发布时间】:2017-06-22 06:58:20
【问题描述】:

this answer 中,我编写了一个LINQ 扩展,它利用了以下delegate,因此我可以传入一个带有out 变量的函数,例如int.TryParse

public delegate bool TryFunc<TSource, TResult>(TSource source, out TResult result);

public static IEnumerable<TResult> SelectTry<TSource, TResult>(
    this IEnumerable<TSource> source, TryFunc<TSource, TResult> selector)
{
    foreach (TSource item in source)
    {
        TResult result;
        if (selector(item, out result))
        {
            yield return result;
        }
    }
}

为了使用这个扩展,我必须像这样显式指定&lt;string, int&gt; 类型:

"1,2,3,4,s,6".Split(',').SelectTry<string, int>(int.TryParse); // [1,2,3,4,6]

我想删除&lt;string, int&gt;,类似于我们可以在不指定&lt;int&gt; 的情况下调用.Select(int.Parse),但是当我这样做时,我收到以下错误:

无法从用法推断方法“LINQExtensions.SelectTry(IEnumerable, LINQExtensions.TryFunc)”的类型参数。尝试明确指定类型参数。


我的问题是,为什么不能推断类型?我的理解是编译器应该知道 int.TryParse 的签名,然后是 TryFunc delegate 在编译时。

【问题讨论】:

标签: c# linq delegates


【解决方案1】:

无法推断,因为只有一个参数适合,那就是字符串。第二个参数是out int,它不能在泛型参数中指定,这就是为什么它说不能推断参数。

在不指定参数的情况下调用SelectTry 的唯一方法是在某个指向int.TryParse 的地方声明您的委托,然后将其作为您的参数传入。

我知道这不是你想要的,这是我知道的唯一可以绕过指定参数的方法。

TryFunc<string, int> foo = int.TryParse;
var s = "1,2,3,4,s,6".Split(',').SelectTry(foo);

请记住,为了将方法作为委托传递,参数必须匹配 1:1。 int.TryParse 匹配 TryFunc,但不匹配 SelectTry

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多