好的,现在我遇到了一个非常奇怪的错误。我正在尝试反序列化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);


c# - Json反序列化对象错误-LMLPHP

我不知道为什么。这是我的位置课程

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将始终相同,而!=将始终返回false。我也不知道为什么。

提前致谢!!!

最佳答案

您的问题来自以下两行:

public Location eventLocation = Location.NoLocation;
public Location targetLocation = Location.NoLocation;


发生这种情况是因为您将两个对象都绑定到一个特定的对象NoLocation。这意味着eventLocation和targetLocation都指向堆内存中的同一对象,更改其中一个也会更改另一个。

将NoLocation更改为这样可以解决您的问题:

public static Location NoLocation { get { return new Location(-1, -1); } }

10-07 21:17