只需添加主類,這裏面的擴展類:
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 ??? –
值改變,但它們總是整數。 –