【问题标题】:IEnumerable vs List in a cshtml filecshtml文件中的IEnumerable vs List
【发布时间】:2020-07-07 14:03:05
【问题描述】:

我想问一下,假设我有一个 cshtml 代码

@model List<Product>
<!DOCTYPE html>
<html lang="en">
<head>

这样就没有问题了。我的问题是我可以写IEnumerable&lt;Product&gt; 而不是List&lt;Product&gt; 在这两种情况下我的程序都可以工作,那么我应该更喜欢哪一个?为什么?

【问题讨论】:

  • 如果您只想遍历模型,请使用 IEnumerable&lt;T&gt;,因为它更通用,并且允许后面的代码更改并传递除 List&lt;T&gt; 之外的其他内容。

标签: c# .net asp.net-core razor


【解决方案1】:

IEnumerable 是比 ICollection、IList 和 List 更通用的类型。

如果您没有使用任何方法,例如“AddRange”(仅适用于 List)或“Add”(仅适用于 IList(和 List)),但您只需要使用您应该喜欢的 foreach 循环遍历集合IEnumerable。

这允许您使用 IEnumerable 的任何实现,例如 List 或 HashSet:

public ActionResult MyAction() {
    List<Product> list = GetProducts();
    return View(list); //works in both cases (IEnumerable and List)
}

public ActionResult MyAction() {
    HashSet<Product> list = GetProducts();
    return View(list); //does not work if you declare the cshtml Model as List
}

public ActionResult MyAction() {
    IEnumerable<Product> products = GetProducts();
    return View(products); // works only if you declare the Model as IEnumerable
}

也就是说,如果您将模型声明为 Product 的 IEnumerable,您不必担心将要使用的实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2013-09-24
    • 2014-04-21
    • 1970-01-01
    相关资源
    最近更新 更多