简体   繁体   English

我可以用IEnumerable编写此lambda吗 <T> 而不是IEnumerable <string> ?

[英]Can I write this lambda with IEnumerable<T> rather than IEnumerable<string>?

Is it possible to write this lambda in a more generic way? 是否可以以更通用的方式编写此lambda? It works fine, but seems too specifically typed; 它可以正常工作,但是看起来过于具体。 the content of the IEnumerable s are not touched, but should be preserved in the return type. IEnumerable的内容未触及,但应保留在返回类型中。

static readonly Func<
    (IEnumerable<string>, IEnumerable<string>),
    (IEnumerable<string>, IEnumerable<string>),
    (IEnumerable<string>, IEnumerable<string>)
> JoinListTuples = (a, b) =>
    (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));

I was thinking of something like this, but it doesn't compile: 我在想像这样的东西,但它不能编译:

static readonly Func<
    (IEnumerable<T>, IEnumerable<U>),
    (IEnumerable<T>, IEnumerable<U>),
    (IEnumerable<T>, IEnumerable<U>)
> JoinListTuples = (a, b) =>
    (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));

Types can be generic, methods can be generic, but fields cannot be generic. 类型可以是通用的,方法可以是通用的,但字段不能是通用的。

A workaround when you really need to have this generically as a delegate type is to make it a field of a generic class: 当您真正需要将其作为委托类型时,一种变通方法是使它成为通用类的字段:

public static class HelperClass<T, U> {
    public static readonly Func<
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>)
    > JoinListTuples = (a, b) =>
        (a.Item1.Concat(b.Item1),
            b.Item2.Concat(b.Item2));
}

But for most purposes, it would suffice to just turn it into a method instead. 但是对于大多数目的,只需将其转换为方法就足够了。 Perhaps something like this: 也许是这样的:

static (IEnumerable<T>, IEnumerable<U>) JoinListTuples<T, U>(
    (IEnumerable<T>, IEnumerable<U>) a,
    (IEnumerable<T>, IEnumerable<U>) b)
{
    return (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));
}

I'm not sure if this will help you 我不确定这是否对您有帮助

However, something like this maybe 但是,这样的事情也许

public class SomeHelper<T,U>
{

    public static readonly Func<
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>)> 
            JoinListTuples = (a, b) => 
               (a.Item1.Concat(b.Item1),b.Item2.Concat(b.Item2));

}

Note, untested and not in front of VS 注意,未经测试,不在VS的前面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM