我在使用BinaryFormatter实际序列化这一个字段时遇到了一些麻烦。
我有一个Tile类,我序列化了它的位置和ID,然后我使用BinaryFormatter保存所有这些tile。每个其他字段都是非序列化的,并使用ID的值进行初始化。
但是,ID字段只是序列化了,但其他一切都没有。可能是什么原因造成的?
这是我的Tile字段:
// The ID of this tile
private int id;
// The name visible for the tile in the map editor
[NonSerialized] private String name;
// The file location for this tile for loading a texture
[NonSerialized] private String fileName;
// Sprite for drawing this tile
[NonSerialized] private Sprite sprite;
private Transform transform = new Transform();
// If this tile is blocked, blocked tiles can not be walked over are classes as "unpassable"
[NonSerialized] private bool blocked;
// Used to determine if a specific tower types can be placed on this tile, if any
[NonSerialized] private short towerMask;
// The tower that is placed on this tile, if any
[NonSerialized] private Tower tower;
// A path generated for enemies to navigate from this tile to another, used for tiles that can spawn enemies
[NonSerialized] private Path path;
当我加载地图时,我这样做:
map = MapSerializer.Load("test");
MapSerializer类只是常用的设置,具有静态加载和保存方法,如下所示:
public static Map Load(string filename){
Map map;
String path = Path.Combine("maps/", filename+".mp");
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);
try{
Trace.WriteLine("Loading map from " + path, "Map Serialization");
map = (Map) formatter.Deserialize(stream);
Trace.WriteLine("Map Loaded!", "Map Serialization");
}
finally{
stream.Close();
}
return map;
}
另一个令人讨厌的是,当加载tile时,它不会调用no args构造函数。那是什么?我必须手动遍历所有的tile并调用Create(),尽管它在no args构造函数中被调用。
任何一个int字段没有写入光盘的想法?
编辑:
序列化代码:
public static void Save(Map data, String filename){
String path = Path.Combine("maps/", filename + ".mp");
BinaryFormatter formatter = new BinaryFormatter();
if (!Directory.Exists("maps"))
Directory.CreateDirectory("maps");
FileStream stream = File.Open(path, FileMode.Create);
try{
Trace.WriteLine("Writing map to " + path, "Map Serialization");
formatter.Serialize(stream, data);
Trace.WriteLine("Map Saved!", "Map Serialization");
}
catch (SerializationException e){
Trace.WriteLine("Failed to save map : Error - " + e.Message);
throw;
}
finally{
// Close the file
stream.Close();
}
}
答案 0 :(得分:0)
您尚未发布序列化代码。到第二期......
序列化不会调用默认构造函数。如果实现ISerializable,则将调用采用序列化特定参数的构造函数。
另一种方法是实现System.Runtime.Serialization.IDeserializationCallback。详情请见link。
另一种方法是使用OnDeserialized属性装饰方法。