WXMC/.svn/pristine/70/704fbc9e3cb67833e959de19131f6b64e3147078.svn-base
2024-12-04 16:18:46 +08:00

128 lines
3.3 KiB
Plaintext

using CommonSerializeDefine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace CommonSerializing
{
public class SerializerBase
{
private SerializeSetting m_settings;
public SerializeSetting Settings
{
get
{
return m_settings;
}
set
{
m_serializers = null;
m_settings = value;
}
}
private Dictionary<Type, ITypeSerializer> m_serializers;
protected ITypeSerializer EnsureSerializer(Type type)
{
ITypeSerializer result = TryGetSerializer(type);
if (result == null)
{
throw new Exception($"Cannot find a serializer fot type {type}");
}
return result;
}
protected ITypeSerializer TryGetSerializer(Type type)
{
if (m_serializers == null)
{
m_serializers = new Dictionary<Type, ITypeSerializer>();
}
ITypeSerializer result = null;
if (m_serializers.TryGetValue(type, out result))
{
return result;
}
foreach (var item in GetAllSerializers())
{
if (item.CanSerialize(type))
{
m_serializers.Add(type, item);
return item;
}
}
return result;
}
protected FieldInfo EnsureField(Type type, string fieldName)
{
FieldInfo result = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (result == null)
{
throw new Exception($"Cannot found field {fieldName} in {type}");
}
return result;
}
protected IEnumerable<ITypeSerializer> GetAllSerializers()
{
if (m_settings.AdditionalSerializers != null)
{
foreach (var item in m_settings.AdditionalSerializers)
{
yield return item;
}
}
foreach (var item in StaticSerializers.TypeSerializers)
{
yield return item;
}
}
protected static string[] SplitPath(string path)
{
string[] result = path.Split('.');
return result;
}
protected static string JoinString(string sep, IEnumerable<string> parts, int count = -1)
{
if (parts == null) return string.Empty;
using var enumerator = parts.GetEnumerator();
var sb = new StringBuilder();
bool hasNext = enumerator.MoveNext();
for (int i = 0; hasNext && (count == -1 || i < count); i++)
{
if (i > 0)
{
sb.Append(sep);
}
sb.Append(enumerator.Current);
hasNext = enumerator.MoveNext();
}
return sb.ToString();
}
}
public struct SerializeSetting
{
public List<ITypeSerializer> AdditionalSerializers;
}
}