创建类实例的方法

里克

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

我有三种类型:

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

我需要将此功能添加到OnBeforeSerialize才能为每个字典值运行:

对于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功能?谢谢你们

-里克

这是课程:

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

创建一个具有GuidToString方法的接口

interface IGuidToStringable {
    void GuidToString();
}

具有RoomDataAssetData并且SegData都实现了接口。

限制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什么都不返回,但是它的名字表明它确实返回了一个字符串。您是否考虑过重命名?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章