• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

什么是csharp代码的可数字

用户头像
it1352
帮助1

问题说明

大家好,



我在一本书中发现了一个csharp代码无法理解你能告诉它IEnumerable是什么。为什么它在这里添加



Hi Guys ,

I found a csharp code in a book which am not able to understand can you please tell what it is IEnumerable . why its added here

@foreach (Album a in (ViewBag.Albums as IEnumerable)) {
@a.Title
 }



< br $>


在此先感谢你们的支持



我的尝试:



需要知道什么是IEnumerable。为什么它在这段代码中使用




Thanks In Advance Guys

What I have tried:

Need to know what is IEnumerable . why its used in the used in this code

正确答案

#1
它可能就在那里(这是猜测)因为视图代码不知道ViewBag.Albums是什么类型的编译时(因为ViewBag是一个动态对象)所以如果你尝试循环通过无法循环的东西,视图将无法编译。通过将as IEnumerable放入,它将把ViewBag.Albums转换为IEnumerable,允许对象循环通过。这允许视图编译,但是如果控制器在ViewBag.Albums中放入一些无法转换为IEnumerable的内容,则会出现运行时错误。



这些问题的更好解决方案是使用强类型的正确模型,以便视图知道Model.Albums在编译时的类型。
It's probably there (this is a guess) because the view code doesn't know what type ViewBag.Albums is at compile time (because ViewBag is a dynamic object) so the view won't compile if you try and loop through something that can't be looped through. By putting "as IEnumerable" it is going to cast ViewBag.Albums to IEnumerable which allows the object to be looped through. This allows the view to compile, however if the controller puts something in ViewBag.Albums that can't be cast to IEnumerable you'll get a run-time error.

A better solution to these issues is to use a proper model which is strongly-typed so the view would know what type Model.Albums is at compile time.
IEnumerable是一个通用集合枚举值(即对象列表)。代码将动态对象ViewBag.Albums作为泛型集合进行转换,然后使用foreach命令遍历每个枚举。
IEnumerable is a generic collection of enumerated values (i.e., a list of objects). The code is casting the dynamic object ViewBag.Albums as a generic collection and then going through each enumeration by using the foreach command.
RTFM [ ^ ]

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfggee
系列文章
更多 icon
同类精品
更多 icon
继续加载