我刚刚开始使用 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/