Terraria ModLoader  0.11.7.8
A mod to make and play Terraria mods
TagSerializable.cs
Go to the documentation of this file.
1 using System;
2 
3 namespace Terraria.ModLoader.IO
4 {
5  //implement this interface and add
6  //public static Func<TagCompound, ClassName> DESERIALIZER
7  //to your class to make it automatically serializable
8  public interface TagSerializable
9  {
10  TagCompound SerializeData();
11  }
12 
13  internal class TagSerializableSerializer<T> : TagSerializer<T, TagCompound> where T : TagSerializable
14  {
15  private Func<TagCompound, T> deserializer;
16 
17  public TagSerializableSerializer() {
18  var type = typeof(T);
19  var field = type.GetField("DESERIALIZER");
20  if (field != null) {
21  if (field.FieldType != typeof(Func<TagCompound, T>))
22  throw new ArgumentException(
23  $"Invalid deserializer field type {field.FieldType} in {type.FullName} expected {typeof(Func<TagCompound, T>)}.");
24 
25  deserializer = (Func<TagCompound, T>)field.GetValue(null);
26  }
27  }
28 
29  public override TagCompound Serialize(T value) {
30  var tag = value.SerializeData();
31  tag["<type>"] = value.GetType().FullName;
32  return tag;
33  }
34 
35  public override T Deserialize(TagCompound tag) {
36  if (tag.ContainsKey("<type>") && tag.GetString("<type>") != Type.FullName) {
37  var instType = GetType(tag.GetString("<type>"));
38  TagSerializer instSerializer;
39  if (instType != null && Type.IsAssignableFrom(instType) && TryGetSerializer(instType, out instSerializer))
40  return (T)instSerializer.Deserialize(tag);
41  }
42 
43  if (deserializer == null)
44  throw new ArgumentException($"Missing deserializer for type '{Type.FullName}'.");
45 
46  return deserializer(tag);
47  }
48  }
49 }