Serialization.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace COM3D2.MeidoPhotoStudio.Plugin
  6. {
  7. public static class Serialization
  8. {
  9. private static readonly Dictionary<Type, ISerializer> Serializers;
  10. private static readonly Dictionary<Type, ISimpleSerializer> SimpleSerializers;
  11. static Serialization()
  12. {
  13. var types = (from t in typeof(MeidoPhotoStudio).Assembly.GetTypes()
  14. let baseType = t.BaseType
  15. where !t.IsAbstract && !t.IsInterface && baseType?.IsGenericType == true
  16. select new { type = t, baseType }).ToArray();
  17. Serializers = types.Where(t => t.baseType.GetGenericTypeDefinition() == typeof(Serializer<>))
  18. .Select(t => new {t.type, arg = t.baseType.GetGenericArguments()[0]})
  19. .ToDictionary(x => x.arg, x => (ISerializer)Activator.CreateInstance(x.type));
  20. SimpleSerializers = types.Where(t => t.baseType.GetGenericTypeDefinition() == typeof(SimpleSerializer<>))
  21. .Select(t => new {t.type, arg = t.baseType.GetGenericArguments()[0]})
  22. .ToDictionary(x => x.arg, x => (ISimpleSerializer)Activator.CreateInstance(x.type));
  23. }
  24. public static Serializer<T> Get<T>() => Serializers[typeof(T)] as Serializer<T>;
  25. public static ISerializer Get(Type type) => Serializers[type];
  26. public static SimpleSerializer<T> GetSimple<T>() => SimpleSerializers[typeof(T)] as SimpleSerializer<T>;
  27. public static ISimpleSerializer GetSimple(Type type) => SimpleSerializers[type];
  28. public static short ReadVersion(this BinaryReader reader) => reader.ReadInt16();
  29. public static void WriteVersion(this BinaryWriter writer, short version) => writer.Write(version);
  30. }
  31. }