Googleに「最速のシリアル化c#」とランダムに入力していたところ、protobuf.netが得られました。やってみたけどちゃんとシリアライズできると思うけどまだデシリアライズできないからわからないよね?!
デシリアライズしようとすると、次のようになります。
A first chance exception of type 'ProtoBuf.ProtoException' occurred in protobuf-net.dll
涼しい。
シリアル化するデータ:
[ProtoContract]
public struct Cow
{
[ProtoMember(1)]
public float Weight{ get; private set; }
[ProtoMember(2)]
public bool[] HadCowlings{ get; private set; }
public Cow(float weight, bool[] babies)
: this()
{
this.Weight = weight;
this.HadCowlings= (bool[])babies.Clone();
}
...
}
[ProtoContract]
public class Pasture
{
[ProtoMember(1)]
public Point Position { get; private set; }
[ProtoMember(2)]
public Cow[] Cows { get; private set; }
public static int HerdSize { get; private set; }
public static float BoundWidth { get; private set;}
public static float BoundHeight { get; private set; }
public Pasture(Cow[] Cows, Point farmPosition)
{
this.Cows = (Cow[])Cows.Clone();
Position = farmPosition;
}
...
}
[ProtoContract]
public class Farm
{
[ProtoMember(1)]
public Point FarmIDCoordinates{ get; private set; }
[ProtoMember(2)]
public List<Pasture> Pastures{ get; private set; }
public static float BoundWidth { get; private set; }
public static float BoundHeight { get; private set; }
public static int FarmSize { get; private set; }
public Farm(int x, int y, FarmType fType)
{
if (fType == RegionType.STANDARD)
Pastures = new List<Pasture>(//make a farm!);
else
Pastures = new List<Pasture>(//What he said);
FarmIDCoordinates = new Point(x, y);
}
...
}
方法:
設定:
using (ObjectSerializer serializer = new ObjectSerializer())
{
serializer.ProtoSerialize<Farm>(farm.ToString() + ".bin", aFarm)
}
得る:
using (ObjectSerializer serializer = new ObjectSerializer())
{
try
{
farmsIOwn.Add(serializer.ProtoDeserialize<Farm>(
farmLat.X.ToString() + "_" + farmLong.Y.ToString() + ".bin"));
}
catch
{
// make me a dummy farm, crashing is for dummies
}
}
ObjectSerializer:
public void ProtoSerialize<T>(string fileName, T objectGraph)
{
using (var stream = File.Open(fileName, FileMode.Create))
{
Serializer.Serialize<T>(stream, objectGraph);
}
}
public T ProtoDeserialize<T>(string fileName)
{
T objectGraph;
using (var stream = File.Open(fileName, FileMode.Open))
{
objectGraph = Serializer.Deserialize<T>(stream);
}
return objectGraph;
}