什么是csharp代码中的可数字 [英] What is ienumerable in csharp code

查看:109
本文介绍了什么是csharp代码中的可数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我在一本书中发现了一个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

推荐答案

它可能就在那里(这是猜测)因为视图代码不知道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 [ ^ ]


这篇关于什么是csharp代码中的可数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆