假設我有一個方法:
private ObservableCollectionExtended<Record> myCollection;
public void SetLoadingProperty(bool isLoading)
{
if (!myCollection?.Any() ?? false)
return;
foreach(var record in myCollection)
{
record.IsLoading = isLoading;
}
}
是否有任何情況下我myCollection在 foreach 回圈中得到 NullReferenceException 為空?
uj5u.com熱心網友回復:
您只需要在您的方法中進行空檢查:
private ObservableCollectionExtended<Record> myCollection;
public void SetLoadingProperty(bool isLoading)
{
if (myCollection == null)
return;
foreach(var record in myCollection)
{
record.IsLoading = isLoading;
}
}
如果您的集合不包含任何專案,則不會執行回圈。檢查Any是沒有必要的。始終嘗試撰寫盡可能簡單的代碼。
在線演示:https ://dotnetfiddle.net/ComNsN
uj5u.com熱心網友回復:
你的意思是:
if (!(myCollection?.Any() ?? false))
return;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450979.html
上一篇:從自定義int計算百分比
