如何在 C# 中保存随机生成器的状态? [英] How to save the state of a Random generator in C#?

查看:27
本文介绍了如何在 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# 中保存随机生成器的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆