如何保存在C#随机生成器的状态? [英] How to save the state of a Random generator in C#?
问题描述
有关测试目的我正在与一个给定的种子产生的随机数(即,不是基于当前时间)。
For testing purposes I'm creating random numbers with a given seed (i.e. not based on the current time).
因此,整个程序是确定性的。
Thus the whole program is deterministic.
如果有事,我希望能够在事件前不久快速恢复的一个点。
If something happens, I'd like to be able to quickly restore a point "shortly before" the incident.
因此,我需要能够恢复 System.Random
到以前的状态。
Therefore I need to be able to restore a System.Random
to a previous state.
有一个方法来提取的种子,我可以用它来重新创建随机数发生器?
Is there a way to extract a seed which I can use to recreate the random generator?
推荐答案
在与answer 这里给出的,我写了一个小班,以帮助保存和恢复状态。
In line with the answer given here, I wrote a small class to help with saving and restoring the state.
void Main()
{
var r = new Random();
Enumerable.Range(1, 5).Select(idx => r.Next()).Dump("before save");
var s = r.Save();
Enumerable.Range(1, 5).Select(idx => r.Next()).Dump("after save");
r = s.Restore();
Enumerable.Range(1, 5).Select(idx => r.Next()).Dump("after restore");
s.Dump();
}
public static class RandomExtensions
{
public static RandomState Save(this Random random)
{
var binaryFormatter = new BinaryFormatter();
using (var temp = new MemoryStream())
{
binaryFormatter.Serialize(temp, random);
return new RandomState(temp.ToArray());
}
}
public static Random Restore(this RandomState state)
{
var binaryFormatter = new BinaryFormatter();
using (var temp = new MemoryStream(state.State))
{
return (Random)binaryFormatter.Deserialize(temp);
}
}
}
public struct RandomState
{
public readonly byte[] State;
public RandomState(byte[] state)
{
State = state;
}
}
您可以测试的 LINQPad 。
这篇关于如何保存在C#随机生成器的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!