产量回报

mp3909

众所周知的成员
加入
2018年4月22日
消息
61
地点
英国
编程经验
3-5
你好,

1)。只想确认,你只能用吗?"yield return"在返回类型的方法内部的语句"IEnumerable"?

2)。我在某个地方读取阵列和列表是枚举物品,所以这是否意味着我可以使用"yield return"返回数组的方法内的语句?

3)。可以是返回类型的方法"IEnumerable"在其签名之前有一个显式访问修饰符?

4)。我看到了一种具有返回类型的方法"IEnumerable"但它返回一个列表<int>。我没有得到这个?而且你不是不是将函数声明为列表<int> in the first place?

谢谢你。
 
Last edited:

约翰

C#论坛主持人
工作人员
加入
2011年4月23日
消息
1,159
地点
挪威
编程经验
10+

jmplhinney.

C#论坛主持人
工作人员
加入
2011年4月23日
消息
3,723
地点
悉尼,澳大利亚
编程经验
10+
迭代器的点是一次返回一个令人令人令人纪念的项目列表。理解这一点"one at a time" part and why it's useful, consider the Directory.GetFilesDirectory.EnumerateFiles methods being used to search your hard drive for a file with particular properties. The GetFiles method will get the path of every file in a folder first, put them all into an array and return that. That might take some time to do, and it might be that you find a matching file very early in that array, in which case a lot of time and effort was wasted getting the rest of the files. The EnumerateFiles method, on the other hand, will return the path of a file as it is available. That means that there is very little wait to be able to start processing the files and, if you find a match and stop the enumeration, no more file paths will be retrieved. In situations like this, the iterator's "one at a time"方法意味着更少等待,可能更少的工作。

The point of the 产量回报 statement is to return one item. Using it to return an array makes no sense, unless your method returns an enumerable list of arrays. In the previous example, GetFiles gets all the file paths, puts them into an array and returns that with a return statement. On the other hand, the EnumerateFiles methods returns one file path at a time with the 产量回报 statement. The way iterators work is that, if you have a 产量回报 x; statement then the return type of the method should generally be Ienumerable.<T> where T is the type of x, e.g. if x is a string then the method's return type should be Ienumerable.<string>.

The Ienumerable.Ienumerable.<T> interfaces exist primarily to be used with foreach loops. Developers will often write a method that returns one of those types if they intend for the result to be enumerated with such a loop. By doing so, it would enable them to change their implementation later to return a different type, e.g. they could implement an iterator instead of returning a concrete list, without breaking any code that calls the method. It also makes the returned list effectively read-only. If such a method returned an array or 列表<T> then the caller could modify the list before using it. As an Ienumerable. or Ienumerable.<T> can only be enumerated and not have its items accessed at random, modifying the list is not really possible. You could always determine the actual type of the object at run time and cast or use Reflection or whatever but that is more effort and not so likely to be done mistakenly or smuggled in maliciously.
 
最佳 底部