How can i get a string and return each time a string from array?

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

I have this function :

private string offline(string targetDirectory)         {             string directory = "";              try             {                 string[] dirs = Directory.GetDirectories(targetDirectory,"*.*",SearchOption.TopDirectoryOnly);                 for (int i = 0; i < dirs.Length; i++)                 {                     directory = dirs[i];                 }             }             catch             {              }             return directory;          } 

For example if targetDirectory is c:\ then i get in the array 14 directories. Now i want that each time i call the function offline it will return me once the first string c:\$Recycle.Bin Then it will return c:\test and each time i call the function it will return the next string from the array. Since im using a recrusive function and calling this offline function from a recrusive i want it to return each time the next string from the array.

Now as it is now it will return the last directory in the array only and thats it.

How can i do it ?

回答1:

Easiest way - use yield:

IEnumerable<string> offline(string dir) {     ...     ... instead of directory = dirs[i] do     yield return dirs[i]; } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!