只需添加主类,这里面的扩展类:
public static class Extensions
{
public static int randomOne(this List<int> theList)
{
Random rand = new Random(DateTime.Now.Millisecond);
return theList[rand.Next(0, theList.Count)];
}
}
然后调用它:
int value = mylist.randomOne();
编辑:这是一个测试程序,演示如何使用该方法。请注意,由于Random的使用不正确,它会产生非常不平衡的结果,100个以上的50个“随机”数字是相同的。
class Program
{
static void Main(string[] args)
{
var myList = Enumerable.Range(0, 100).ToList();
var myRandoms = myList.Select(v => new { key = v, value = 0 })
.ToDictionary(e => e.key, e => e.value);
for (int i = 0; i < 100; i++)
{
var random = myList.RandomOne();
myRandoms[random]++;
}
Console.WriteLine(myRandoms.Values.Max());
Console.ReadLine();
}
}
要解决该问题,请在Extension程序中使用随机静态实例或在程序中更广泛地共享。这在FAQ for Random中讨论。
public static class Extensions
{
static Random rand = new Random();
public static int randomOne(this List<int> theList)
{
return theList[rand.Next(0, theList.Count)];
}
}
什么是在randMoveDecider ??? –
值改变,但它们总是整数。 –