我的方法返回一個包含對象列表的響應對象。將對象列表複製到另一個對象中另一個對象的另一個列表中
public class GetAccountsListResponse
{
public List<AccountsList> Accounts { get; set; }
}
public class AccountsList
{
public string AccountId { get; set; }
public string AccountName { get; set; }
}
我想這樣的事情,但即時得到空refernce例外:
public GetAccountsListResponse GetAccountsList()
{
AccountRepository objRepo = new AccountRepository();
GetAccountsListResponse res = new GetAccountsListResponse();
List<Account> lstAccnts = new List<Account>();
lstAccnts = objRepo.GetAccountsFromRepo();
foreach (var item in lstAccnts)
{
res.Accounts = new List<AccountsList>();
res.Accounts.ForEach(c => c.AccountId = item.AccountId);
}
return res;
}
請幫我解決這個問題。
在哪一行,你收到此 –
貌似lstAccnts *力量*趕回來空的調用'objRepo.GetAccountsFromRepo()'。 – Baldrick
'res.Accounts = new List(); res.Accounts.ForEach(c => c.AccountId = item.AccountId);'這兩行沒有意義。你創建'新的List <>'和'ForEach'?它將始終有零元素 –