好的,现在我遇到了一个非常奇怪的错误。我试图反序列化一个GameEvent对象,如下所示:
public class GameEvent {
public Location eventLocation = Location.NoLocation;
public Location targetLocation = Location.NoLocation;
public string eventTriggerName = ""; // Who (Piece or tactic) triggers this event
public string targetTriggerName = ""; // Target name
public int eventPlayerID = -1;
public int targetPlayerID = -1;
public string result = ""; // Piece, Tactic, Trap, Freeze, Move, Kill, Flag
public int amount = 0;
public GameEvent() { Debug.Log("Fuck"); }
public static string ClassToJson(GameEvent gameEvent)
{
return JsonConvert.SerializeObject(gameEvent);
}
}
但是,当我通过这样做反序列化时,它会发生奇怪的变化。
public static GameEvent JsonToClass(string json)
{
Debug.Log(json);
GameEvent gameEvent = JsonConvert.DeserializeObject<GameEvent>(json);
Debug.Log(ClassToJson(gameEvent));
return JsonConvert.DeserializeObject<GameEvent>(json);
}
从下图中可以看出,eventLocation应该是(7,2)但是在反序列化后它变为(4,2)。而且eventLocation是唯一被改变的东西。
string json = "{\"eventLocation\": {\"x\": 7, \"y\": 2}, \"targetLocation\": {\"x\": 4, \"y\": 2} }";
var x = GameEvent.JsonToClass(json);
我不知道为什么。这是我的位置类
public class Location
{
public int x = -1;
public int y = -1;
public Location(){}
public Location(int X, int Y)
{
x = X;
y = Y;
}
public Location(Location location)
{
x = location.x;
y = location.y;
}
public static bool operator !=(Location a, Location b)
{
UnityEngine.Debug.Log(a + " " + b);
return a.x != b.x || a.y != b.y;
}
public static Location NoLocation = new Location(-1, -1);
}
我没有发布GameEvent和Location类的所有功能,但我发布了他们拥有的所有变量。
顺便说一下,我还遇到了另一个奇怪的位置问题。当我执行if(eventLocation != Location.NoLocation)
时,我覆盖的!=运算符实际上并不是将eventLocation与Location.NoLocation进行比较,而是将eventLocation(是的本身)进行比较。所以a和b总是一样的!= =总是会让我失意。我也不知道为什么。
提前致谢!!!
答案 0 :(得分:3)
你的问题来自这两行:
public Location eventLocation = Location.NoLocation;
public Location targetLocation = Location.NoLocation;
这种情况正在发生,因为您将两个对象绑定到NoLocation的特定对象。这意味着eventLocation和targetLocation都指向堆内存中的同一个对象,并且更改其中一个也会改变另一个对象。
将NoLocation更改为此类可以解决您的问题:
public static Location NoLocation { get { return new Location(-1, -1); } }