简体   繁体   English

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

[英]How to specify parameter for generic list type extension method in c#

I am trying to make an extension method that will shuffle the contents of a generic list collection regardless of its type however im not sure what to put in between the <..> as the parameter. 我正在尝试创建一个扩展方法,该方法将对通用列表集合的内容进行洗牌而不管其类型如何,但我不确定在<..>之间放置什么作为参数。 do i put object? 我把对象? or Type? 或类型? I would like to be able to use this on any List collection i have. 我希望能够在我拥有的任何List集合中使用它。

Thanks! 谢谢!

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);
    }
}

You need to make it a generic method: 你需要使它成为通用方法:

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);
    }
}

That will allow it to work with any List<T> . 这将允许它与任何List<T>

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

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

Slightly off-topic, but a Fisher-Yates shuffle will have less bias and better performance than your method: 稍微偏离主题,但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;
    }
}

I Think this solution faster to process, because you will get your itens randomly and your collection position will be preserved to future use. 我觉得这个解决方案的处理速度更快,因为你会随机获得你的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;
        }
    }
}

Steps: 脚步:

  1. Create your Static Class to Identify your extensions 创建静态类以识别您的扩展
  2. Create you Extension Method (must be static) 创建扩展方法(必须是静态的)
  3. Process your data. 处理您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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