は単純にメインクラス内でこの拡張クラスを追加します。あなたのシナリオでは、それを使用しての
public static Random _rand = new Random();
public IEnumerable<T> Randomise<T>(IList<T> list)
{
while(true)
{
// we find count every time since list can change
// between iterations
yield return list[_rand.Next(list.Count)];
}
}
一つの方法:
// as a field somewhere so it's initialised once only
public Random _r = new Random();
// later in your code
var _randList = new List<int>{4,5,8,9};
var _move = _r.Next(_randList.Count);
return _randList[_move];
さらに良いことに、ここでは任意のリストをランダム化します何かがあります:
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();
EDIT:このメソッドをどのように使用するかを示すテストプログラムです。ランダムの誤った使用のために、それは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で議論されています。 randMoveDeciderにあるもの
public static class Extensions
{
static Random rand = new Random();
public static int randomOne(this List<int> theList)
{
return theList[rand.Next(0, theList.Count)];
}
}
??? –
値は変わりますが、常に整数です。 –