为类属性分配不同类型
我创建了一个类来存储我正在进行的 API 调用的数据。它返回带有一些元信息的 JSON,然后根据所进行的调用返回一个数据数组。元信息将始终具有相同的字段,因此我为此创建了一个“根”类,但数据会根据所进行的调用而有所不同,因此我为每种类型的数据创建了不同的类,例如用户数据、公司数据等。如下所示,我当前将“数据”属性设置为对象列表,但我试图找出合并可返回的不同类型数据的最佳方法,因为它将根据所拨打的电话而有所不同。
现在,我已将数据保存为对象列表,但我希望根据我收到的数据进行更改。就像,如果我要检索用户,我希望它是用户列表。
适应这种情况的理想方式是什么?我现在能想到的唯一方法是为我期望接收的每种类型的数据创建一个不同的“根”类,但这并不觉得它应该是最简洁的方法。我正在考虑将其作为工厂设计模式,但我不确定它是否适合这种情况。
I have created a class to store data from API calls I am making. It returns JSON with some meta information, and then an array of data depending on the call being made. The meta information will always have the same fields, so I have created a "Root" class for this, but the data will be different depending on the call being made, so I have created different classes for each type of data, e.g. user data, company data, etc. As shown below, I currently have the "data" property set to a list of objects, but I am trying to figure out the best way to incorporate the different types of data that can be returned, since it will vary based on the call being made.
Right now I have the data saved as a list of objects, but I would like this to change depending on what data I am receiving. Like, if I am retrieving users, I would like for it to be a list of users.
What is the ideal way to accommodate for this? The only way I can think to do it now is to create a different "Root" class for every type of data I am expecting to receive, but that doesn't feel like it should be the most concise way to do it. I was looking into making this a factory design pattern but I wasn't sure that it fit this scenario.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用通用基类:
然后为每个 api 调用定义一个结果。
在这里创建了一个小的工作示例:
dotnet 小提琴
Just use a generic base class:
Then define a result per api call.
Created a small working example here:
dotnet fiddle