块中的返回类型不可隐式转换

时间:2018-06-18 08:19:24

标签: c# delegates higher-order-functions

您好我正在尝试实现我自己的高阶扩展但我无法理解为什么聚合(fold)会出现以下错误:

错误:

Cannot convert lambda expression to intended delegate
type because some of the< return types in the block are not implicitly convertible to the delegate return type.

我不明白为什么它说返回类型不匹配。我用作seedList<object>并在Fold中为每个元素添加元素到列出并返回List<Object>

分机类:

public static class HOrder
{
    public static IEnumerable<U> Map<T,U>(this IEnumerable<T> collection, Func<T, U> transform)
    {
        var map = collection.Select(transform);
        return map;
    }
    public static TAccumulate Fold<TAccumulate,TSource>(this IEnumerable<TSource>source,TAccumulate seed,Func<TAccumulate,TSource,TAccumulate>aggregate)
    {
        var fold = Enumerable.Aggregate(source, seed, aggregate);
        return fold;

    }
    internal static object Extractor(Node node)
    {
        object result;
        switch (node.Kind)
        {
            case Node.Discriminator.String: result = node.AsStirng.Value; break;

            case Node.Discriminator.Integer: result = node.AsInteger.Value; break;

            case Node.Discriminator.Array: result = 
                 HOrder.Fold<Node,List<object>>(
                        node.AsArray.Items, 
                        new List<object>(), 
                        (x, y) => { y.Add(Extractor(x)); return y; } //<--Error at return y
                        );
             break;

            default:throw new NotImplementedException();
        }
        return result;
    }
}

P.S :错误在return y上突出显示。

1 个答案:

答案 0 :(得分:0)

我通过将通用参数从Fold<List<object>>,Node>切换为interface CheckedFunction<I, O> { O apply(I i) throws Exception; } static <I, O> Function<I, O> unchecked(CheckedFunction<I, O> f) { return i -> { try { return f.apply(i); } catch(Exception ex) { throw new RuntimeException(ex); } } } fileNamesToRead.map(unchecked(file -> Files.readAllLines(file))) 来解决了这个问题。