【发布时间】:2018-11-23 19:51:02
【问题描述】:
我在 c# 中有一个用于字典的通用类,但是我想为字典的不同实例/类型添加 OnBeforeSerialize() 功能。
我有三种类型:
SerializableDictionary<Guid, RoomData>
SerializableDictionary<Guid, AssetData>
SerializableDictionary<Guid, SegData>
我需要将此功能添加到 OnBeforeSerialize 以针对每个字典值运行:
对于房间数据:
public void GuidToString() {
roomData.guid = guid.ToString();
roomData.assetGuidList.Clear();
roomData.assetGuidList=assetGuidList.Select(g => g.ToString()).ToList();
}
对于资产数据:
public void GuidToString() {
assetData.guid = guid.ToString();
assetData.segGuidArray=segGuidArray.Select(g => g.ToString()).ToArray();
assetData.roomGuid = roomGuid.ToString();
}
对于分段数据:
public void GuidToString() {
segData.guid = guid.ToString();
if (door != null) {
segData.returnWallGuid = door.returnWall.guid.ToString();
}
}
如何确保相关的 GuidToString 功能与相应类型的 SerializableDictionary 一起运行?谢谢大家
-瑞克
这是课程:
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
[SerializeField]
private List<TKey> keys = new List<TKey>();
[SerializeField]
private List<TValue> values = new List<TValue>();
// save the dictionary to lists
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach(KeyValuePair<TKey, TValue> pair in this)
{
keys.Add(pair.Key);
values.Add(pair.Value);
}
}
// load dictionary from lists
public void OnAfterDeserialize()
{
this.Clear();
if(keys.Count != values.Count)
throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable."));
for(int i = 0; i < keys.Count; i++)
this.Add(keys[i], values[i]);
}
}
【问题讨论】:
-
约束
TValue以实现提供对GuidToString函数的访问的接口。然后在你的类中实现该接口RoomData, AssetData, ...,你可以在序列化过程中调用它。 -
您使用的是什么序列化?
[Serializable]已经很老了。 -
thehennyy 说的对我来说听起来不错。
-
我正在使用可序列化的统一..我认为这是将东西保存到 json 的唯一方法
标签: c# generics serializable