繁体   English   中英

使用简单对象自定义复杂C#对象的血清

[英]Custom serilization of a complex C# object using simple objects

我正在使用QuickGraph的一个名为AdjacencyGraph的实用程序类,它具有复杂的内部结构。

我不关心复杂类的所有内部属性,我不能将其更改为来自nuget包 - 最多在我的数据库中我只关心存储可用于重建AdacencyGraph的Dependency对象数组:

public class Dependency
{
    public Dependency(string source, string target)
    {
        this.Source = source;
        this.Target = target;
    }

    public string Source { get; set; }
    public string Target { get; set; }
}

在序列化时,我需要做的就是以下代码:

void Serialize(Dependencies toSerialize)
{
    var toBeStored = toSerialize.GetAllDependencies();
    // write this to mongodb somehow
}

反序列化构建Dependencies对象:

Dependencies Deserialize(IEnumerable<Dependency> hydrateFrom)
{
    var dependencies = new Dependencies();

    foreach(var d in hydrateFrom)
    {
        dependencies.SetRequiresFor(d.Source, d.Target);
    }
}

我该如何拦截序列化过程和输出?

其他信息

我已经在一个列出所有Dependency对象的类中包装了AdjacencyGraph,并且也可以接受一个Dependency对象列表。

class Dependencies
{
    private AdjacencyGraph<string, Edge<string>> relationshipGraph = new AdjacencyGraph<string, Edge<string>>();

    public void SetRequiresFor(SkuId on, SkuId requires)
    {
        var toAdd = new Edge<string>(on.Value, requires.Value);
        this.relationshipGraph.AddVerticesAndEdge(toAdd);

    }

    public IEnumerable<Dependency> GetAllDependencies()
    {
        foreach(var edge in this.relationshipGraph.Edges)
        {
            yield return new Dependency(edge.Source, edge.Target);
        }
    }
}

您需要做三件事:

  1. 实现BsonSerializer
  2. 实现一个BsonSerializationProvider ,它将Dependencies指向序列化程序。 *
  3. 在应用程序的初始化中注册提供程序。

BsonSerializer

public class DependenciesBsonSerializer : BsonBaseSerializer
{
    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        // implement using bsonWriter
    }

    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        // implement using bsonReader
    }
}

BsonSerializationProvider

public sealed class BsonSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        if (type == typeof(Dependncies)
        {
            return new DependenciesBsonSerializer ();
        }

        return null;
    }
}

Registeration

BsonSerializer.RegisterSerializationProvider(new BsonSerializationProvider());

*您可以使用BsonSerializer.RegisterSerializer直接剪切提供程序并注册序列化程序,但我仍然建议将所有序列化程序分组到一个提供程序中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM