如何在 C# 中保存随机生成器的状态?

编程入门 行业动态 更新时间:2024-10-27 02:29:34
本文介绍了如何在 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?

推荐答案

符合 这里给出的答案,我写了一个小类来帮助保存和恢复状态.

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# 中保存随机生成器的状态?

本文发布于:2023-11-10 09:21:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生成器   状态   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!