c# - 为什么在 get 方法之前需要 IEnumerable<string> ?

标签 c# asp.net api

我刚刚开始使用 ASP.NET 学习 Web API。我从 Visual Studio 创建了一个新项目,并尝试了解 MVC 文件夹结构和 API 调用。

这里我想知道的是:为什么我们需要IEnumerable<string>之前get方法。

在我的ValuesController.cs ,

        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

根据Microsoft Documentation ,这公开了枚举器,它支持对指定类型的集合进行简单迭代,但想想如果我的数据库中有一个整数,我是否也需要将其转换为字符串?

最佳答案

IEnumerable<string>返回类型为 Get() Action 方法。如果您的 api 返回任何值,那么您需要将该类型指定为函数的返回类型

If I have an integer in my database do I need to convert it into string as well?

  • ,那么您可以返回给定的整数,并且该 api 端点的返回类型将为 int ,

喜欢,

    //+ Access Modifier
    //|     + Return Type           
    //|     |    + Function name
    public int Get()
    {
        return 200; //status code for Ok.
    }
<小时/>

关于IEnumerable<> :

如果您有多个整数并希望返回这些整数的集合,请使用 IEnumerable<int>

来自 MSDN 文档 IEnumerable Interface :

Exposes an enumerator, which supports a simple iteration over a non-generic collection.

关于c# - 为什么在 get 方法之前需要 IEnumerable<string> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505291/

相关文章:

c# - 在 .NET 2.0 中序列化私有(private)支持数据成员?

c# - 我无法定义 "client"SignalR

c# - 如何创建 XML 字符串而不是使用字符串生成器?

c# - 从上传的 Excel 文件中获取数据而不保存到文件系统

r - 如何在 R 代码中集成 Google 距离矩阵 API key ?

javascript - 页面导航到 localhost :3000/? 在输入框中输入按下

c# - LINQ 查询中的自定义排序

c# - Datagridview 选择我通过数据库插入的最后一个插入行

c# - 在 asp :panel in jquery 中找到控件

ios - 有没有办法通过 Apple 后端的一些 API 导出应用商店应用内支付?