简体   繁体   English

返回与泛型类相同的类型

[英]Return same Type as Generic Class

Wasn't really sure how to phrase the title. 真的不确定如何用语表达标题。

What I am trying to achieve is a deep clone system for IEnumerable<T> s where T:ICloneable . 我想要实现的是针对IEnumerable<T>的深克隆系统,其中T:ICloneable

I have written the, as-yet untested, method below which I believe should work: 我已经编写了一种尚未通过测试的方法,我认为该方法应该可以工作:

    public static IEnumerable<T> DeepClone<T>(this IEnumerable<T> source) where T:ICloneable
    {
        return source.Select(s => (T) s.Clone());
    }

However, this returns an IEnumerable<T> (as one would expect) and I am curious as to whether or not it is possible (without causing an unacceptable overhead) to return the base type of the IEnumerable<T> instead. 但是,这将返回一个IEnumerable<T> (正如人们所期望的那样),我很好奇是否有可能(不会造成不可接受的开销)返回IEnumerable<T>的基本类型。

For example, running List<int>.DeepClone() would return a new, cloned List<int> and running int[].DeepClone() would return a new, cloned int[] . 例如,运行List<int>.DeepClone()将返回一个新的,克隆的List<int>并运行int[].DeepClone()将返回一个新的,克隆的int[]

I know that I can quite easily just cast my IEnumerable s after calling this method, but I'm hoping to be able to avoid this. 我知道调用此方法后可以很容易地转换IEnumerable ,但是我希望能够避免这种情况。

There is also the option of creating a whole load of overloads, one for each IEnumerable but if it's possible to I'd like to avoid this. 还有一种选择是创建整个过载,每个IEnumerable加载一个,但是如果可能的话,我想避免这种情况。

You will need to build explicit methods for the concrete types you want to support (List, arrays etc). 您将需要为要支持的具体类型(列表,数组等)构建显式方法。

An example: 一个例子:

public static List<T> DeepClone<T>(this List<T> source) where T : ICloneable
{
    return source.Select(s => (T)s.Clone()).ToList();
}

Alternatively, use an approach like: 或者,使用类似的方法:

public static IEnumerable<T> DeepClone<T>(this IEnumerable<T> source) where T : ICloneable
{
    var result = source.Select(s => (T)s.Clone());

    if (source is List<T>)
    {
        return result.ToList();
    }

    return result;
}

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

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