【发布时间】:2014-10-10 11:32:03
【问题描述】:
我正在尝试复制同一类的两个不同实例,没有引用,我不知道为什么这很难做到,只需复制就可以了,再见?
顺便说一句,我找到了一个带有 binnaryformatter 的脚本,它可以满足我的要求,但是在我的班级中,我有一个 Texture2D 类型的变量,当我按下播放键时,我有一个错误,说 Texture2D 没有被标记为可序列化。
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
public class pichota : MonoBehaviour {
public List<Pig> johnPigList = new List<Pig>();
public List<Pig> peterPigList = new List<Pig>();
void Start () {
List<Pig> templist = Clone(johnPigList);
peterPigList = templist;
}
public List<Pig> Clone(List<Pig> source)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, source);
ms.Seek(0, 0);
return (List<Pig>)bf.Deserialize(ms);
}
}
void Update () {
if (Input.GetKeyDown(KeyCode.G))
{
peterPigList[0].number += 2;
}
}
}
[System.Serializable]
public class Pig
{
public int number;
}
还有另一种深拷贝的方法,或者只是序列化纹理 2d 吗?不要笑我,我是这个高级东西的新手
【问题讨论】:
-
添加更多关于要复制哪个类的信息。是不是来自你自己的代码,成员的范围等等。
-
为什么不做一个 Pig 构造函数,将 Pig 作为参数并复制构造函数中的成员?
-
哇鲁道夫,我花了一天一夜试图解决这个问题,这是一个非常简单的解决方案!
-
拥有一个名为 deepcopy 或 shallowcopy 的函数比克隆或复制构造函数更好,因为它应该是显而易见的
-
@Imapler,您的命名约定在理论上更好,但现实要求您将混合(浅和深)成员副本,因此它从来没有您建议的那么简单。事实上,按照您的命名约定,他最终可能会使用 deepcopy、deepcopy 和 notsodeepcopy 函数来描述他在做什么。
标签: c# generics serialization unity3d binaryformatter