出于测试目的,我使用给定的种子(即不基于当前时间)创建随机数.
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?
推荐答案符合 这里给出的答案,我写了一个小类来帮助保存和恢复状态.
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 中测试此代码.
You can test this code in LINQPad.
更多推荐
如何在 C# 中保存随机生成器的状态?
发布评论