C# 如何在c中为泛型列表类型扩展方法指定参数#
我正在尝试创建一个扩展方法,该方法将洗牌泛型列表集合的内容,而不管其类型如何,但是我不确定在作为参数的。我放东西了吗?还是类型?我希望能够在我拥有的任何列表集合中使用此功能 谢谢C# 如何在c中为泛型列表类型扩展方法指定参数#,c#,generics,parameters,extension-methods,C#,Generics,Parameters,Extension Methods,我正在尝试创建一个扩展方法,该方法将洗牌泛型列表集合的内容,而不管其类型如何,但是我不确定在作为参数的。我放东西了吗?还是类型?我希望能够在我拥有的任何列表集合中使用此功能 谢谢 public static void Shuffle(this List<???????> source) { Random rnd = new Random(); for (int i = 0; i < source.Count; i++) { int in
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);
}
}
publicstaticvoidshuffle(此列表源代码)
{
随机rnd=新随机();
for(int i=0;i
您需要使其成为一种通用方法:
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);
}
}
publicstaticvoidshuffle(此列表源代码)
{
随机rnd=新随机();
for(int i=0;i
这将允许它处理任何
列表
您只需将自己的方法设置为通用:
public static void Shuffle<T>(this List<T> source)
publicstaticvoidshuffle(此列表源代码)
稍微偏离主题,但a将比您的方法具有更少的偏差和更好的性能:
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;
}
}
publicstaticvoidshuffleinplace(此IList源代码)
{
如果(source==null)抛出新的ArgumentNullException(“source”);
var rng=新随机数();
for(int i=0;i
我认为此解决方案处理起来更快,因为您将随机获得您的iTen,并且您的收集位置将保留以备将来使用
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;
}
}
}
名称空间MyNamespace
{
公共静态类MyExtensions
{
公共静态T GetRandom(此列表源)
{
随机rnd=新随机();
int index=rnd.Next(0,source.Count);
T o=源[索引];
返回o;
}
}
}
步骤:
我得学着打字快一点。无论如何,
IList
将更加通用。当我尝试列出的所有方法时,我得到。。。参数“2”:不能从“对象”转换为“t”格兰特:需要改变中间部分使用“t”而不是“对象”(或添加一个CAST)。正如John所提到的,使用IList更为通用,尽管并非所有IList都实现插入,因此它可能无法正常工作。IList
具有Insert
方法。什么类实现了IList,而没有实现Insert?@John:ICollection.IsReadOnly设置为true的任何实现通常在Insert时抛出。我以前吃过这种东西。见: