我有以下代碼:如何在不跳過合法循環的情況下處理nullreferenceexception?
foreach (SPListItem item in list.Items)
{
string itemId = item.ID.ToString();
string contentType = item.ContentType.ToString();
string displayName = item.DisplayName;
string name = item.Name;
// todo: Title not always retreiving? Likely due to folders, needs more handling
//string title = item["Title"].ToString() ?? null;
string title = "";
string url = item.Url;
string author = item["Created By"].ToString();
// todo: Checked out files catering
const string checkedOutBy = "";
DateTime lastModified = Convert.ToDateTime(item["Modified"]);
string lastModifiedBy = item["Modified By"].ToString();
DateTime created = Convert.ToDateTime(item["Created"]);
query.RecordItems(itemId, contentType,
displayName, name,
title, url, author,
checkedOutBy,
lastModified,
lastModifiedBy,
created,
author);
}
我的問題是環路標題或ContentType的一些迭代將拋出一個NullReferenceException,但不是所有的人。我相信我已經滿足了以下要求,但我不確定 - 有沒有更好的方法?
foreach (SPListItem item in list.Items)
{
try
{
string itemId = item.ID.ToString();
string contentType = item.ContentType.ToString();
string displayName = item.DisplayName;
string name = item.Name;
// todo: Title not always retreiving? Likely due to folders, needs more handling
//string title = item["Title"].ToString() ?? null;
string title = "";
string url = item.Url;
string author = item["Created By"].ToString();
// todo: Checked out files catering
const string checkedOutBy = "";
DateTime lastModified = Convert.ToDateTime(item["Modified"]);
string lastModifiedBy = item["Modified By"].ToString();
DateTime created = Convert.ToDateTime(item["Created"]);
query.RecordItems(itemId, contentType,
displayName, name,
title, url, author,
checkedOutBy,
lastModified,
lastModifiedBy,
created,
author);
}
catch (NullReferenceException ex)
{
Logger.Error("[{0}] Filed moving on file {1} as not all content was present", item.Name);
}
}
的http:// msdn.microsoft.com/en-us/library/bb687949(v=office.12).aspx請收集一些SharePoint最佳實踐。例如'不要枚舉整個SPList.Items集合' –