[英]How to decide for type of a property when creating an instance?
I'm coding an online game in Unity.我正在使用 Unity 编写在线游戏。 I'm also using a custom response shape for my HTTP responses, like below:我还在为我的 HTTP 响应使用自定义响应形状,如下所示:
public class Response
{
public string status;
public List<string> messages;
public List<T> data;
}
I want to decide on the type of "data" property when I receive an HTTP response.当我收到 HTTP 响应时,我想决定“数据”属性的类型。 It can be any custom type.它可以是任何自定义类型。 for example from type player:例如来自类型播放器:
public class Player
{
public string id;
public string name;
public int gems;
public Player(string id, string name, int gems)
{
this.id = id;
this.name = name;
this.gems = gems;
}
}
so the shape of response, in this case, will be like below:因此,在这种情况下,响应的形状将如下所示:
public class Response
{
public string status;
public List<string> messages;
public List<Player> data;
}
so I can parse and assign it like:所以我可以像这样解析和分配它:
var player = JsonUtility.FromJson<Response>(response.ReadAsString()).data[0];
or for other use cases like:或用于其他用例,例如:
var players = JsonUtility.FromJson<Response>(response.ReadAsString()).data;
but it will be different for each response around the code and I don't want to create so many classes for each.但是围绕代码的每个响应都会有所不同,我不想为每个响应创建这么多的类。
Is this even possible?这甚至可能吗? What are the options or/and the best way?有哪些选择或/和最好的方法? How can I implement it?我该如何实施?
Not sure if Unity likes that but you could try and make the Response
class generic不确定 Unity 是否喜欢这样,但您可以尝试使Response
class 通用
[Serializable]
public class Response<T>
{
public string status;
public List<string> messages;
public List<T> data;
}
and then use然后使用
var players = JsonUtility.FromJson<Response<Player>>(response.ReadAsString()).data;
var player1 = players[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.