我正在尝试深度克隆包含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)