简体   繁体   English

AsEnumerable()与“作为IEnumerable” <T> ”

[英]AsEnumerable() vs. “as IEnumerable<T>”

What is the difference between 之间有什么区别

(db.Records as IEnumerable<Record>).Where(...)

and

(db.Records.AsEnumerable()).Where(...).

Is AsEnumerable() a shortcut for source as IEnumerable<T> only? AsEnumerable()是仅source as IEnumerable<T>快捷方式吗?

I've read https://msdn.microsoft.com/en-us/library/bb335435(v=vs.90).aspx , but did't find any info about it. 我已经阅读https://msdn.microsoft.com/en-us/library/bb335435(v=vs.90).aspx ,但是没有找到有关它的任何信息。

The difference is that you can call AsEnumerable on an IEnumerable<T> where T is an anonymous type, and you couldn't perform such a cast on such a sequence, since you can't type out the name of a type that has no name. 区别在于,您可以在IEnumerable<T>上调用AsEnumerable ,其中T是匿名类型,并且您无法对此类序列执行此类强制转换,因为您无法键入不具有该类型的类型的名称名称。 This ability of AsEnumerable to infer the generic argument is the reason for it to exist. AsEnumerable推断通用参数的这种能力是其存在的原因。

(It's also arguably cleaner syntax, but outside of anonymous types that's not a functional difference, merely a personal preference.) (它可以说是更简洁的语法,但是在匿名类型之外,这不是功能上的区别,只是个人喜好。)

There are two relevant sections on that article. 该文章有两个相关部分。

First, 第一,

The AsEnumerable(IEnumerable) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable to IEnumerable itself. AsEnumerable(IEnumerable)方法除了将源的编译时类型从实现IEnumerable的类型更改为IEnumerable本身之外没有任何作用。

And second, 其次,

If remote execution is not desired, for example because the predicate invokes a local method, the AsEnumerable method can be used to hide the custom methods and instead make the standard query operators available. 如果不需要远程执行,例如因为谓词调用了本地方法,则可以使用AsEnumerable方法隐藏自定义方法,并使标准查询运算符可用。

In other words, yes, it looks like a shortcut. 换句话说,是的,它看起来像一个捷径。 However, it is meant to enforce in memory operations of Where and other IEnumerable<T> methods versus the actual implementations of the underlying type. 但是,这意味着要在内存中强制执行Where和其他IEnumerable<T>方法与基础类型的实际实现的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM