为类的实例创建方法

时间:2018-06-14 06:06:50

标签: c# generics serializable

我在c#中有一个字典的泛型类,但是我希望为字典的不同实例/类型添加OnBeforeSerialize()的功能。

我有三种类型:

SerializableDictionary<Guid, RoomData>
SerializableDictionary<Guid, AssetData>
SerializableDictionary<Guid, SegData>

我需要将这个功能添加到OnBeforeSerialize以运行每个字典值:

for RoomData:

    public void GuidToString() {
        roomData.guid = guid.ToString();
        roomData.assetGuidList.Clear();
        roomData.assetGuidList=assetGuidList.Select(g => g.ToString()).ToList();
    }

对于AssetData:

public void GuidToString() {
    assetData.guid = guid.ToString();
    assetData.segGuidArray=segGuidArray.Select(g => g.ToString()).ToArray();
    assetData.roomGuid = roomGuid.ToString();
}

对于SegData:

public void GuidToString() {
    segData.guid = guid.ToString();
    if (door != null) {
        segData.returnWallGuid = door.returnWall.guid.ToString();
    }
}

如何确保使用相应类型的SerializableDictionary运行相关的GuidToString功能?谢谢你们

-Rik

这是班级:

 [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]);
     }
 }

1 个答案:

答案 0 :(得分:2)

创建一个具有GuidToString方法的界面:

interface IGuidToStringable {
    void GuidToString();
}

RoomDataAssetDataSegData都实现接口。

限制TValue成为IGuidToStringable的实施者:

public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver where TValue : IGuidToStringable

现在您可以致电GuidToString

 public void OnBeforeSerialize()
 {
     keys.Clear();
     values.Clear();
     foreach(KeyValuePair<TKey, TValue> pair in this)
     {
         pair.Value.GuidToString();
         keys.Add(pair.Key);
         values.Add(pair.Value);
     }
 }

我看到GuidToString没有返回任何内容,但它的名字暗示它确实返回一个字符串。你考虑过重命名吗?