本人开发过程中碰到过的情况,需要创建一个引用类型(GameData)变量的临时变量(TempData)。
但是众所周知如果直接永等于号赋值(GameData= TempData),那么无疑它们两个都将指向同一地址,改变其中任何一个,两个都将一起改变于是采用深度复制的方法
首先该类要序列化
[System.Serializable]
public class GameData
{
public bool IsNewGame;
public float MusicValue;
public float SoundValue;
public Resolution[] Resolutions;
public int ResolutionIndex;
public bool IsFullScreen;
public bool IsDebug;
//默认值
public GameData()
{
ResolutionIndex = 0;
IsNewGame = false;
MusicValue = 0.5f;
SoundValue = 0.5f;
IsFullScreen = false;
IsDebug = true;
Resolutions = new Resolution[] {
new Resolution(1920,1080),
new Resolution(1080,720),
new Resolution(2580,1080),
};
}
}
然后写一个复制使用类
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Clone {
public static T DeepCopy<T>(T source) {
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
使用
这样data和temp指向不同的内存区域