2016-06-28 108 views
2

我创建了一些扩展方法,我想在不同的集合上使用这些扩展方法,主要是那些实现IList和数组集合[]当我创建一个扩展方法时,我需要创建2而不是1,以便它可以同时为通用扩展方法C#

public static IList<T> Shuffle<T>(this IList<T> inputCollection) 
    { 

    } 

    public static T[] Shuffle<T>(this T[] inputCollection) 
    { 

    } 

工作我的大多数方法需要与索引工作,所以我不能用IEnumerable是没有办法,我可以写仅有1扩展方法,并用它为双方所期望的藏品一些其他的方式?有时我也使用string这是另一种方法。

+0

如果你要返回一个新的集合,那么IEnumerable <>就足够了。但是,你确实不想这么做,所以ICollection <>是正确的。 –

+2

数组实现'IList ',所以你可能不需要其中的一个(取决于实现)。 –

+0

选项1是使用由数组和'List '实现的非泛型'IList'接口,另一个选项是为实现IList 的数组创建包装,但是可以从下层数组读取和写入,在array ext方法中,您可以'new包装(数组).ListExtMethod()' – csharpfolk

回答

6

您可以尝试

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> value) 

签名;并用它

IList<T> list = Shuffle(myList).ToList(); 
T[] array = Shuffle(myArray).ToArray(); 

甚至

IList<T> list = myList.Shuffle().ToList(); 
T[] array = myArray.Shuffle().ToArray(); 
+0

但是,如果我使用'这个IEnumerable 价值'我不能申请索引在我的方法。 – PreqlSusSpermaOhranitel

+0

@PreqlSusSpermaOhranitel:把它翻译成数组,例如:T [] data = value.ToArray();' –

+0

伟大的解决了我的问题! – PreqlSusSpermaOhranitel

0

我会建议使用这种扩展方法,因为所有的List对象从IEnumerable继承。

public static IEnumerable<T> MethodName<T>(this IEnumerable<T> value)