我怎样才能得到一个字符串,每次从数组返回一个字符串? [英] How can i get a string and return each time a string from array?

查看:119
本文介绍了我怎样才能得到一个字符串,每次从数组返回一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

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;

        }

例如,如果targetdirectory中为c:\然后我得到在阵列14的目录。
现在我想,我每次调用函数下线将返回我一次第一串c:\ $ RECYCLE.BIN
然后,它会返回C:\test
和各一次,我调用函数会从数组返回下一个字符串。
因为即时通讯使用recrusive函数调用从recrusive我希望它每次从数组的下一个字符串返回此脱机功能。

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.

我该怎么办呢?

推荐答案

最简单的方法 - 使用收益

Easiest way - use yield:

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

这篇关于我怎样才能得到一个字符串,每次从数组返回一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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