我正在寻找一种方法来从包含相同元素的旧集合创建新集合。通用方法来创建任何集合的副本(与匹配类型)
对于HashSet<T>
它的工作原理是这样的:
HashSet<T> oldSet = ... // consider it filled with elements
HashSet<T> newSet = new HashSet<T>(oldSet);
对于List<T>
它类似于:
List<T> oldList = ... // consider it filled with elements
List<T> newList = new List<T>(oldList);
据我所知,所有ICollection<T>
实现有这种类型的拷贝构造函数。
有没有一种方法(现在我们称之为CreateCopy
),它对所有ICollection<T>
都这样做?为什么我可以这样称呼它?
ICollection<T> oldColl = ... // can be List, HashSet, ...
ICollection<T> newColl = oldColl.CreateCopy(); // will have the same type as oldColl
如果不是,我该如何编写自己的方法来实现这个目标?这使我心中唯一的想法是这样的:
public static ICollection<T> CreateCopy<T>(this ICollection<T> c)
{
if (c is List<T>) return new List<T>(c);
else if (c is HashSet<T>) return new HashSet<T>(c);
else if ...
}
但当然,这是一个可怕的解决方案 - 每当一个新的执行ICollection<T>
恶有恶报,我需要更新方法...
顺便说一句,你不能创建通用的扩展方法 – MetaColon
@MetaColon是的,我可以。当我用例如'...'替换最后一行'else if ...'时,'CreateCopy'方法编译时没有错误。 'else return null;' – Kjara
我不知道你是如何设法达到这个目的的。 https://stackoverflow.com/a/9238156/7700150 – MetaColon