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

时间:2009-08-15 01:10:08

标签: 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);
    }
}

4 个答案:

答案 0 :(得分: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);
    }
}

这将允许它与任何List<T>一起使用。

答案 1 :(得分:4)

您只需将自己的方法设为通用:

public static void Shuffle<T>(this List<T> source)

答案 2 :(得分:3)

稍微偏离主题,但Fisher-Yates shuffle的偏见和性能会比您的方法更少:

public static void ShuffleInPlace<T>(this IList<T> source)
{
    if (source == null) throw new ArgumentNullException("source");

    var rng = new Random();

    for (int i = 0; i < source.Count - 1; i++)
    {
        int j = rng.Next(i, source.Count);

        T temp = source[j];
        source[j] = source[i];
        source[i] = temp;
    }
}

答案 3 :(得分:0)

我觉得这个解决方案的处理速度更快,因为你会随机获得你的itens,你的收藏位置将被保留以备将来使用。

namespace MyNamespace
{
    public static class MyExtensions
    {
        public static T GetRandom<T>(this List<T> source)
        {
            Random rnd = new Random();
            int index = rnd.Next(0, source.Count);
            T o = source[index];
            return o;
        }
    }
}

步骤:

  1. 创建静态类以识别您的扩展程序
  2. 创建扩展方法(必须是静态的)
  3. 处理您的数据。