如何在c#中指定通用列表类型扩展方法的参数

Gra*_*ant 5 c# generics parameters extension-methods

我正在尝试创建一个扩展方法,该方法将对通用列表集合的内容进行洗牌而不管其类型如何,但我不确定在<..>之间放置什么作为参数.我把对象?或类型?我希望能够在我拥有的任何List集合中使用它.

谢谢!

public static void Shuffle(this List<???????> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        object o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 11

你需要使它成为通用方法:

public static void Shuffle<T>(this List<T> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        T o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许它与任何List<T>.

  • 我必须学会更快地打字.无论如何,`IList <T>`会更一般. (4认同)
  • @Grant:您需要更改中间的部分以使用"T"而不是"object"(或添加演员).正如John所提到的,使用IList <T>会更通用,虽然并非所有IList <T>都实现插入,因此它可能无法正常工作. (2认同)