我需要用protobuf序列化/反序列化一个KeyedCollection,我可以只序列化一个列表吗?
如果是这样的话,将列表转换回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; }
}发布于 2022-02-09 02:04:37
解决办法?
.NET平台扩展6有一个KeyedCollection,KeyedByTypeCollection类的实现。这里有构造者,它接受IEnumerable。这种实现的缺点是,键是项,它似乎不允许您更改这些项。如果您已经继承了KeyedCollection,那么您最好遵循实现这里并遵循微软的领导;他们只是迭代和调用Add()。
另请参阅
以前的思想
我还试图从Linq查询的角度来解决这个问题,可能是相关的文章:
核心问题似乎是KeyedCollectedion不包含采用任何形式的ICollection来初始化其数据的构造函数。但是,KeyedCollection的基类集合是这样做的。唯一的选项似乎是为您的KeyedCollection类编写自己的构造函数,它遍历集合并将每个元素添加到当前实例中。
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class VariableList<T> : KeyedCollection<string, T>
{
// KeyedCollection does not seem to support explicitly casting from an IEnumerable,
// so we're creating a constructor who's sole purpose is to build a new KeyedCollection.
public VariableList(IEnumerable<T> items)
{
foreach (T item in items)
Add(item);
}
// insert other code here
}虽然这看起来很低效,所以我希望有人纠正我.
编辑:约翰·佛朗哥( John )写了一个博客,他们在其中黑出了一个解决方案,可以通用地使用协变(2009年!)这看起来不是一种很好的做事方式。
查看System.Linq.EnDigable的实现 of ToList,Linq还迭代并添加到新集合中。
https://stackoverflow.com/questions/46445284
复制相似问题