简体   繁体   中英

Generic Extension Methods C#

I'm creating a few extension methods that i want to use on different collections mostly those that implement IList and array collections [] whenever im creating an extension method i need to create 2 instead of just 1 so that it can work for both

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

    }

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

    }

Most of my methods require work with the indexes so i cant use IEnumerable is there some other way that i can write just 1 extension method and use it for both of the desired collections ? Also sometimes i use the string which is one more method.

You can try

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

signature; and use it

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

or even

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

我建议使用此扩展方法,因为所有List对象都是从IEnumerable继承的。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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