dotNet Core 5 API Service将对象添加到列表中,但结果具有最后一项的多个副本



dotNet Core 5 c# Web API项目,Service类添加对象(基于视图模型)到列表。在构建对象并将其添加到List时,调试显示所有数据都是正确的,但是返回的结果只有添加的最后一项的多个副本(匹配它应该具有的计数)。下面的服务代码和视图模型代码。我错过了什么?

using FS.Data.Repositories;
using FS.Models;
using FS.ViewModels;
using FS.ViewModels.APVendor;
using Microsoft.Extensions.Options;
using NLog;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace FS.Services
{
public class GLAccountSetService : IGLAccountSetService
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IOptions<AppSettingsModel> AppSettings;
private readonly HttpClient Client;
GlAccountSetResponseViewModel result = new GlAccountSetResponseViewModel();
public GLAccountSetService(HttpClient client, IOptions<AppSettingsModel> app)
{
Client = client; //?? throw new ArgumentNullException(nameof(client));
AppSettings = app;
}
public async Task<GlAccountSetResponseViewModel> GetGLAccountSets(IList<GlAccountSetRequestViewModel> req, IAPCorpRepository apcr)
{
result.GlAccountSetViewModels = new List<GlAccountSetViewModel>();
result.SuccessErrorWarningResult = new SuccessErrorWarningResult();
GlAccountSetViewModel accountSet = new GlAccountSetViewModel();

string payorID = "";
string payeeID = "";
string payorCashAccount = "";
string payeeCashAccount = "";
string expenseAccount = "";
string offsetAccount = "";
string type = "";            
long reqID = 0;
foreach (GlAccountSetRequestViewModel glr in req)
{
type = glr.Type;
expenseMain = glr.ExpenseAccount;
payorID = glr.PayorCorpID;
payeeID = glr.PayeeCorpID;
reqID = glr.ReqID;
//...skipping calculation code that works

accountSet.ExpenseAccount = expenseAccount;
accountSet.PayorCashAccount = payorCashAccount;
accountSet.PayeeCashAccount = payeeCashAccount;
accountSet.OffsetAccount = offsetAccount;
accountSet.ReqID = reqID;
result.GlAccountSetViewModels.Add(accountSet);                                
}
return result;
}                
}
}
using FS.Common;
using System.Collections.Generic;
namespace FS.ViewModels.APVendor
{
public class GlAccountSetResponseViewModel : FSObject<GlAccountSetResponseViewModel>
{
public IList<GlAccountSetViewModel> GlAccountSetViewModels { get; set; }
public SuccessErrorWarningResult SuccessErrorWarningResult { get; set; }
}
}
namespace FS.ViewModels.APVendor
{
public class GlAccountSetViewModel
{
public string ExpenseAccount { get; set; }
public string PayorCashAccount { get; set; }
public string PayeeCashAccount { get; set; }
public string OffsetAccount { get; set; }
public long ReqID { get; set; }
}
}

您将同一个accountSet实例多次添加到列表中,仅在循环中修改它。因此,列表中对它的所有引用都将"具有"。最近设置的值。

您需要在循环中创建一个新的GlAccountSetViewModel实例并添加它,或者将其设置为struct以便在添加时复制它。