[英]return empty List in catch block
我有 ac# 函數,它從數據表中讀取文件位置,並將包含所有文件位置的列表返回給調用方法。
在Catch
塊中,我想返回一個帶有 false 的空列表,以便調用方法可以取消它的操作。
但是我無法編譯我的return
語句。
將列表作為參考傳遞並讓函數返回布爾值true/false
會更好嗎?
這是我正在嘗試的代碼:
public static List<string> getEmailAttachments(string emailID, System.Data.DataTable emails)
{
List<string> allAttachments;
//System.Data.DataTable oTbl = new DataTable();
try
{
System.Diagnostics.Debugger.Break();
var results = from myRow in emails.AsEnumerable()
where myRow.Field<string>("itemID") == emailID
select myRow;
System.Diagnostics.Debug.Print("attachments");
foreach (DataRow myRow in results)
{
System.Diagnostics.Debug.Print(myRow.Field<string>("attachmentsPath"));
allAttachments.Add(myRow.Field<string>("attachmentsPath"));
//DataTable dt = (DataTable)myRow["attachmentsPath"];
//DataTable oTbl = dt.Clone();
//DataRow[] orderRows = dt.Select("CustomerID = 2");
//foreach (DataRow dr in orderRows)
//{
// oTbl.ImportRow(dr);
//}
// myTable.ImportRow(dr);
//oTbl.Rows.Add(myRow);
//oTbl.ImportRow(myRow);
}
return allAttachments;
}
catch (Exception ex)
{
logBuilder("common.getEmailAttachments", "Exception", "", ex.Message, "");
return new List<string>emptyList(); // cannot compile
}
}
改變這一行:
return new List<string>emptyList(); // cannot compile
到:
return new List<string>();
傳遞一個列表作為引用,並從函數返回一個布爾值,這是一個壞主意。 您的方法稱為getEmailAttachments
,它加載附件,並且應該返回附件。 如果您想檢查加載附件的結果,我建議您返回null
並檢查返回值。
如果有人還在尋找...
使用IEnumerable<string>
作為返回類型並且:
return Enumerable.Empty<string>();
用
return new List<string>();
嘗試這個..
public static List<string> getEmailAttachments(string emailID, System.Data.DataTable emails)
{
List<string> allAttachments;
//System.Data.DataTable oTbl = new DataTable();
try
{
System.Diagnostics.Debugger.Break();
var results = from myRow in emails.AsEnumerable()
where myRow.Field<string>("itemID") == emailID
select myRow;
System.Diagnostics.Debug.Print("attachments");
foreach (DataRow myRow in results)
{
System.Diagnostics.Debug.Print(myRow.Field<string>("attachmentsPath"));
allAttachments.Add(myRow.Field<string>("attachmentsPath"));
//DataTable dt = (DataTable)myRow["attachmentsPath"];
//DataTable oTbl = dt.Clone();
//DataRow[] orderRows = dt.Select("CustomerID = 2");
//foreach (DataRow dr in orderRows)
//{
// oTbl.ImportRow(dr);
//}
// myTable.ImportRow(dr);
//oTbl.Rows.Add(myRow);
//oTbl.ImportRow(myRow);
}
//return allAttachments;
}
catch (Exception ex)
{
logBuilder("common.getEmailAttachments", "Exception", "", ex.Message, "");
allAttachments= new List<string>();
}
return allAttachments;
}
我會采取稍微不同的方法。 我會返回一個空列表,但也將初始容量設置為零!
像這樣:
return new List<string>(0);//notice the initial capacity to zero.
原因是內存消耗和優化......我知道這是一個微優化,但它不會傷害任何東西。 它實際上可能有益於整個應用程序。
關於什么
allAttachments.Clear();
return allAttachments;
自 .Net Framework 4.6 和 Core .Net 版本以來,已經添加了更好的方法,
return Array.Empty<T>();
這將分配一個單一的數組(它是一個 IList),並將它重用於對該類型的空數組的所有后續請求。 它快速,干凈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.