MoTaForPSVita/Assets/Scripts/Framework/Tools.cs

79 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class Tools
{
/// <summary>
/// 深拷贝 通过反射
/// </summary>
/// <typeparam name="T">拷贝类型</typeparam>
/// <param name="obj">拷贝对象</param>
/// <returns>复制体</returns>
public static T DeepCopyByReflect<T>(T obj)
{
//如果是字符串或值类型则直接返回
if (obj == null || (obj is string) || (obj.GetType().IsValueType)) return obj;
object retval = Activator.CreateInstance(obj.GetType());
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); }
catch { }
}
return (T)retval;
}
}
// 序列化 List
[Serializable]
public class Serialization<T>
{
[SerializeField]
List<T> target;
public List<T> ToList() { return target; }
public Serialization(List<T> target)
{
this.target = target;
}
}
// 序列化 Dictionary
[Serializable]
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
{
[SerializeField]
List<TKey> keys;
[SerializeField]
List<TValue> values;
Dictionary<TKey, TValue> target;
public Dictionary<TKey, TValue> ToDictionary() { return target; }
public Serialization(Dictionary<TKey, TValue> target)
{
this.target = target;
}
public void OnBeforeSerialize()
{
keys = new List<TKey>(target.Keys);
values = new List<TValue>(target.Values);
}
public void OnAfterDeserialize()
{
var count = Math.Min(keys.Count, values.Count);
target = new Dictionary<TKey, TValue>(count);
for (var i = 0; i < count; ++i)
{
target.Add(keys[i], values[i]);
}
}
}