我希望能够获得实际状态或种子或System.Random的任何内容,以便我可以关闭一个应用程序,当用户重新启动它时,它只是将其"重新安置"它与存储的一个并继续,就像它从未关闭.
可能吗?
使用Jon的想法,我想出来测试它;
static void Main(string[] args)
{
var obj = new Random();
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("c:\\test.txt", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
for (var i = 0; i < 10; i++)
Console.WriteLine(obj.Next().ToString());
Console.WriteLine();
formatter = new BinaryFormatter();
stream = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
obj = (Random)formatter.Deserialize(stream);
stream.Close();
for (var i = 0; i < 10; i++)
Console.WriteLine(obj.Next().ToString());
Console.Read();
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试深度克隆包含System.Random变量的对象.我的应用程序必须是确定性的,因此我需要捕获随机对象状态.我的项目基于.Net Core 2.0.
我在这里使用了一些深度克隆代码(你如何在.NET(特别是C#)中对对象进行深度复制?)使用序列化.
System.Random的文档是混合的:
序列化
https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx
http://referencesource.microsoft.com/#mscorlib/system/random.cs,bb77e610694e64ca(源代码)
不可序列化
https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.7.1
https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-2.0
我收到以下错误.
System.Runtime.Serialization.SerializationException HResult = 0x8013150C Message =在程序集'System.Private.CoreLib中输入'System.Random',Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 7cec85d7bea7798e'未标记为可序列化.来源= System.Runtime.Serialization.Formatters
System.Random可以按我想要的方式克隆吗?
我创建了一个小程序来说明.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace RandomTest
{
class Program
{
static void Main(string[] args)
{
Container C = new Container();
Container CopyC = DeepClone(C);
}
public static T DeepClone<T>(T obj)
{
using(var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj); //<-- error here
ms.Position …Run Code Online (Sandbox Code Playgroud)