簡體   English   中英

如何在 try catch 塊中返回 IEnumerable object?

[英]How to return IEnumerable object in try catch block?

我有一個方法,它從目錄中讀取所有文件作為字符串,然后遍歷這些文件以獲取文件內容以及其他詳細信息,並從中返回IEnumerable<DataFiles> object ,如下所示:

public IEnumerable<DataFiles> GetFiles(string path)
{
    var listOfFiles = new List<string>();
    try
    {
        var jsonDataFiles = Directory.GetFiles(path, "*.json", SearchOption.AllDirectories);
        var textDataFiles = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
        listOfFiles.AddRange(jsonDataFiles);
        listOfFiles.AddRange(textDataFiles);
        for (int i = 0; i < listOfFiles.Count; i++)
        {
            var cfgPath = listOfFiles[i];
            if (!File.Exists(cfgPath)) { continue; }
            var fileContent = File.ReadAllText(cfgPath);
            var pieces = cfgPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
            var fileName = pieces[pieces.Length - 1];
            var md5HashValue = GetMD5Hash(cfgPath);
            // error on below line
            yield return new DataFiles
            {
                FileName = fileName,
                FileContent = fileContent,
                MD5Hash = md5HashValue
            };
        }
    }
    catch (UnauthorizedAccessException ex)
    {
        // log error here
    }
    // error on below line
    return null;
}

但不知何故,在我的上述方法中,我在yield return new line 和return null行時遇到了編譯錯誤。 以下是我看到的錯誤:

Cannot yield a value in the body of a try block with a catch clause
Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.

如果上面的代碼拋出異常,那么我想返回空的IEnumerable<DataFiles> object 否則它應該返回正確的IEnumerable<DataFiles>對象`,其中包含數據。

我在這里做錯了什么? 有沒有更好更干凈的方法來編寫上述方法,這樣我就不必在方法結束時返回 null ?

正如 Jamiec 所提到的,您應該能夠省略“返回 null”未經授權的異常通常是文件系統錯誤,因此請事先獲取所有文件。 還有第二個 try catch 塊,以防您的處理出錯

public IEnumerable<DataFiles> GetFiles(string path)
    {
        var listOfFiles = new List<string>();
        try
        {
            listOfFiles.AddRange(System.IO.Directory.GetFiles(path, "*.json", System.IO.SearchOption.AllDirectories));
            listOfFiles.AddRange(System.IO.Directory.GetFiles(path, "*.txt", System.IO.SearchOption.AllDirectories));
        }
        catch (UnauthorizedAccessException ex)
        {
            // log error here
        }
        string fileName, fileContent;
        int md5HashValue; // im assuming this is an it, not sure
        //byte[] md5HashValue; // not sure
        for (int i = 0; i < listOfFiles.Count; i++)
        {
            try
            {
                var cfgPath = listOfFiles[i];
                if (!System.IO.File.Exists(cfgPath)) { continue; }
                fileContent = System.IO.File.ReadAllText(cfgPath);
                var pieces = cfgPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
                fileName = pieces[pieces.Length - 1];
                md5HashValue = GetMD5Hash(cfgPath);
            }
            catch (Exception ex)
            {
                // log other error here
                continue;
            }
            // error on below line
            yield return new DataFiles
            {
                FileName = fileName,
                FileContent = fileContent,
                MD5Hash = md5HashValue
            };
        }
    
    }

執行以下步驟:

  • 在 try 塊外為DataFiles聲明類型變量
  • 將數據分配給該變量:
yourDataFilesObj = new DataFiles
                {
                   FileName = fileName,
                   FileContent = fileContent,
                   MD5Hash = md5HashValue
                };

  • 外部 Catch 塊寫入為
yield return yourDataFilesObj;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM