为类属性分配不同类型

发布于 2025-01-11 01:09:38 字数 525 浏览 0 评论 0原文

我创建了一个类来存储我正在进行的 API 调用的数据。它返回带有一些元信息的 JSON,然后根据所进行的调用返回一个数据数组。元信息将始终具有相同的字段,因此我为此创建了一个“根”类,但数据会根据所进行的调用而有所不同,因此我为每种类型的数据创建了不同的类,例如用户数据、公司数据等。如下所示,我当前将“数据”属性设置为对象列表,但我试图找出合并可返回的不同类型数据的最佳方法,因为它将根据所拨打的电话而有所不同。

根类object

现在,我已将数据保存为对象列表,但我希望根据我收到的数据进行更改。就像,如果我要检索用户,我希望它是用户列表。

适应这种情况的理想方式是什么?我现在能想到的唯一方法是为我期望接收的每种类型的数据创建一个不同的“根”类,但这并不觉得它应该是最简洁的方法。我正在考虑将其作为工厂设计模式,但我不确定它是否适合这种情况。

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.

Root class object

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

演出会有结束 2025-01-18 01:09:38

只需使用通用基类:

public abstract class ApiCallResult<T>
{
    // With your properties
    // public int Limit { get; set; }
    // [...]
    //
    public IEnumerable<T> Data { get; set; }
}

然后为每个 api 调用定义一个结果。

public class UserApiCallResult : ApiCallResult<User>
{
}

在这里创建了一个小的工作示例:
dotnet 小提琴

Just use a generic base class:

public abstract class ApiCallResult<T>
{
    // With your properties
    // public int Limit { get; set; }
    // [...]
    //
    public IEnumerable<T> Data { get; set; }
}

Then define a result per api call.

public class UserApiCallResult : ApiCallResult<User>
{
}

Created a small working example here:
dotnet fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文