这是 System.Type 的示例序列化程序,它将 Type 的名称序列化为 BSON 字符串。这有一些限制,如果类型名称不是系统类型或在同一程序集中,则 Deserialize 方法会失败,但您可以调整此示例序列化程序以改为编写 AssemblyQualifiedName。
public class TypeSerializer : IBsonSerializer
{
public object Deserialize(BsonReader reader, Type nominalType, IBsonSerializationOptions options)
{
var actualType = nominalType;
return Deserialize(reader, nominalType, actualType, options);
}
public object Deserialize(BsonReader reader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
if (reader.CurrentBsonType == BsonType.Null)
{
return null;
}
else
{
var fullName = reader.ReadString();
return Type.GetType(fullName);
}
}
public bool GetDocumentId(object document, out object id, out Type idNominalType, out IIdGenerator idGenerator)
{
throw new InvalidOperationException();
}
public void Serialize(BsonWriter writer, Type nominalType, object value, IBsonSerializationOptions options)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteString(((Type)value).FullName);
}
}
public void SetDocumentId(object document, object id)
{
throw new InvalidOperationException();
}
}
诀窍是让它正确注册。您需要为 System.Type 和 System.RuntimeType 注册它,但 System.RuntimeType 不是公共的,因此您无法在代码中引用它。但是您可以使用 Type.GetType 来解决它。这是注册序列化程序的代码:
var typeSerializer = new TypeSerializer();
BsonSerializer.RegisterSerializer(typeof(Type), typeSerializer);
BsonSerializer.RegisterSerializer(Type.GetType("System.RuntimeType"), typeSerializer);
我使用这个测试循环来验证它是否有效:
var types = new Type[] { typeof(int), typeof(string), typeof(Guid), typeof(C) };
foreach (var type in types)
{
var json = type.ToJson();
Console.WriteLine(json);
var rehydratedType = BsonSerializer.Deserialize<Type>(json);
Console.WriteLine("{0} -> {1}", type.FullName, rehydratedType.FullName);
}
其中 C 只是一个空类:
public static class C
{
}