Serialization.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 = new();
  10. private static readonly Dictionary<Type, ISimpleSerializer> simpleSerializers = new();
  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 != null && baseType.IsGenericType
  16. select new { type = t, baseType }).ToArray();
  17. var concreteSerializers = from t in types
  18. where t.baseType.GetGenericTypeDefinition() == typeof(Serializer<>)
  19. select new { t.type, arg = t.baseType.GetGenericArguments().First() };
  20. foreach (var serializer in concreteSerializers)
  21. serializers[serializer.arg] = (ISerializer) Activator.CreateInstance(serializer.type);
  22. var concreteSimpleSerializers = from t in types
  23. where t.baseType.GetGenericTypeDefinition() == typeof(SimpleSerializer<>)
  24. select new { t.type, arg = t.baseType.GetGenericArguments().First() };
  25. foreach (var serializer in concreteSimpleSerializers)
  26. simpleSerializers[serializer.arg] = (ISimpleSerializer) Activator.CreateInstance(serializer.type);
  27. }
  28. public static Serializer<T> Get<T>() => serializers[typeof(T)] as Serializer<T>;
  29. public static ISerializer Get(Type type) => serializers[type];
  30. public static SimpleSerializer<T> GetSimple<T>() => simpleSerializers[typeof(T)] as SimpleSerializer<T>;
  31. public static ISimpleSerializer GetSimple(Type type) => simpleSerializers[type];
  32. public static short ReadVersion(this BinaryReader reader) => reader.ReadInt16();
  33. public static void WriteVersion(this BinaryWriter writer, short version) => writer.Write(version);
  34. }
  35. }