【问题标题】:Return data from self loopoing method in C#从 C# 中的自循环方法返回数据
【发布时间】:2017-02-26 12:39:59
【问题描述】:

我正在编写一个 windows phone 8.1 (winrt) 应用程序。我必须从路径 (string) 中获取 StorageFile。 我正在进入子文件夹,直到我迭代地使用此方法获取文件。 (方法循环直到找到 storageFile)

但是如何返回这个 storageFile 呢? 它从第一次运行(循环)返回 null

 public static async Task<StorageFile> GetStorageFileAsync(StorageFolder currentFolder, string filePath)
        {
            StorageFile file = null;
            if (FileHelper.IfPathContainDirectory(filePath))
            {
                // Just get the folder.
                string subFolderName = Path.GetDirectoryName(filePath);

                bool isSubFolderExist = await FileHelper.IfFolderExistsAsync(currentFolder, subFolderName);

                StorageFolder subFolder=null;

                if (isSubFolderExist)
                { 
                    // Just get the folder.
                    subFolder =
                        await currentFolder.GetFolderAsync(subFolderName);
                }
                else
                {
                   return null;
                }

                string newFilePath = Path.GetFileName(filePath);

                if (!string.IsNullOrEmpty(newFilePath))
                {
                    //get file iteratively.
                    await GetStorageFileAsync(subFolder, newFilePath);
                }
                return file;
            }
            else
            {

                try
                {
                    file = await currentFolder.GetFileAsync(filePath);
                }
                catch(Exception fileExp)
                {

                }

                return file;
            }
        }

进入方法,检查路径字符串中是否存在子文件夹 并深入该子文件夹,最后进入其他部分 条件并获取文件。它不返回这个文件,但它返回 循环第一次执行时对象为 null。

【问题讨论】:

  • 您可以传递一个 StorageFile 类型 (ref) 的第三个参数,并在找到它后分配给它。
  • 异步方法不能有 ref 或 out 参数 :(

标签: c# windows-phone-8 windows-runtime windows-phone-8.1 windows-phone


【解决方案1】:

您忘记分配 file 变量:

await GetStorageFileAsync(subFolder, newFilePath);

应该是

file = await GetStorageFileAsync(subFolder, newFilePath);

没有尝试代码,但这显然是结果为null 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2018-09-07
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多