Protobuf-net KeyedCollection序列化

时间:2017-09-27 10:15:40

标签: c# list serialization protobuf-net keyedcollection

我需要使用protobuf-net序列化/反序列化KeyedCollection,我可以序列化一个列表吗?

如果是这样,将List转换回KeyedCollection的最有效方法是什么?

下面是一个显示案例的示例代码:

public class FamilySurrogate
{
    public List<Person> PersonList { get; set; }

    public FamilySurrogate(List<Person> personList)
    {
        PersonList = personList;
    }


    public static implicit operator Family(FamilySurrogate surrogate)
    {
        if (surrogate == null) return null;

        var people = new PersonKeyedCollection();
        foreach (var person in surrogate.PersonList)  // Is there a most efficient way?
            people.Add(person);

        return new Family(people);

    }

    public static implicit operator FamilySurrogate(Family source)
    {
        return source == null ? null : new FamilySurrogate(source.People.ToList());
    }

}

public class Person
{
    public Person(string name, string surname)
    {
        Name = name;
        Surname = surname;
    }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Fullname { get { return $"{Name} {Surname}"; } }
}

public class PersonKeyedCollection : System.Collections.ObjectModel.KeyedCollection<string, Person>
{        
    protected override string GetKeyForItem(Person item) { return item.Fullname; }
}

public class Family
{
    public Family(PersonKeyedCollection people)
    {
        People = people;
    }

    public PersonKeyedCollection People { get; set; }
}

0 个答案:

没有答案