I've tried using the solutions in this post. Both the property and the surrogate didn't work. The cause would most likely be that protobuf-net doesn't work on dictionary directly but serializes the types a dictionary contains (and a surrogate on object is impossible).Comment désérialiser un dictionnaire générique avec une valeur d'objet dans protobuf-net en utilisant une propriété proxy/shim?
Mon code de test
class Program
{
static void Main(string[] args)
{
var library = new Library();
library.Keeper.Add("Harry Potter", "blablabla text... text...");
library.Keeper.Add("Other book", "Awesome story.");
// Write and read to test serializing.
Library deserialize;
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, library);
ms.Flush();
ms.Position = 0;
deserialize = Serializer.Deserialize<Library>(ms);
}
Console.WriteLine(deserialize.Keeper.Count);
}
}
classe Bibliothèque
[ProtoContract]
public class Library
{
public Dictionary<string, object> Keeper { get; set; }
[ProtoMember(1)]
public Dictionary<string, string> KeeperSer
{
get
{
var res = new Dictionary<string, string>();
foreach (var pair in Keeper)
{
res.Add(pair.Key, TypeDescriptor.GetConverter(pair.Value.GetType()).ConvertToInvariantString(pair.Value));
}
return res;
}
set
{
var set = new Dictionary<string, object>();
foreach (var pair in value)
{
set.Add(pair.Key, pair.Value);
}
Keeper = set;
}
}
public Library()
{
Keeper = new Dictionary<string, object>();
}
}
J'ai aussi essayé d'ajouter [ProtoIgnore] à la propriété Keeper
. L'ajout d'un point d'arrêt au paramètre KeeperSer
ou Keeper
ne se déclenche jamais lors de l'exécution du projet. Les getters fonctionnent et les données sont écrites par protobuf-net au MemoryStream
. La longueur varie également lors de l'ajout de nouveaux éléments au Library
.
La raison pour le Dictionary<string, object>
est que j'utilise TypeDescriptor.GetConverter(Type)
dans un autre projet. Et je veux convertir dynamiquement les types à mon type requis.
Que dois-je faire pour que le setter de la propriété proxy/shim KeeperSer
fonctionne?