作为参数传递的对象未更新
Passed Object as Argument not Being Updated
主持人
这里我调用了一个方法叫"services.UpdateSelectedDeposit(deposit);"。如您所见,它调用了以下服务中的一个方法,该方法调用了存储库中的一个方法来根据 DepositID 设置存款模型。
public void OnDoubleClicked(object sender, EventArgs e)
{
if(addTipView.DataGridView.CurrentRow.Index != -1)
{
deposit.DepositID = Convert.ToInt32(addTipView.DataGridView.CurrentRow.Cells["DepositID"].Value);
Console.WriteLine(deposit.DepositID);
services.UpdateSelectedDeposit(deposit);
Console.WriteLine(deposit.DepositAmount);
addTipView.TxtTipAmount = deposit.DepositAmount.ToString();
addTipView.TxtDate = deposit.DepoistDate.ToString();
addTipView.TxtHoursWorked = deposit.HoursWorked.ToString();
}
}
服务
public void UpdateSelectedDeposit(Deposit deposit)
{
repo.GetSelectedDeposit(deposit);
}
存储库
public void GetSelectedDeposit(Deposit deposit)
{
using (var context = new TipManagerDBEntities())
{
deposit = context.Deposits.Where(x => x.DepositID == deposit.DepositID).FirstOrDefault();
Console.WriteLine(deposit.DepositAmount);
}
}
当我在存储库中打印存款金额时,我得到了正确的值,但是当我在展示器中打印存款金额时,它是不正确的。我作为参数传递的存款 class 是通过引用传递的,对吧?为什么我的值在演示者中不正确。
当将 object 传递给方法(松散使用的术语)时,您实际上传递的是 reference ,但这里的重点是该对象的实际 reference 由 value 传递。意味着更新它(覆盖它)在 调用链 .
中没有任何作用
如果您想覆盖 reference(通过 reference 传递 reference),那么您将需要使用 ref
关键字(在适当的地方)。
public void GetSelectedDeposit(ref Deposit deposit)
主持人 这里我调用了一个方法叫"services.UpdateSelectedDeposit(deposit);"。如您所见,它调用了以下服务中的一个方法,该方法调用了存储库中的一个方法来根据 DepositID 设置存款模型。
public void OnDoubleClicked(object sender, EventArgs e)
{
if(addTipView.DataGridView.CurrentRow.Index != -1)
{
deposit.DepositID = Convert.ToInt32(addTipView.DataGridView.CurrentRow.Cells["DepositID"].Value);
Console.WriteLine(deposit.DepositID);
services.UpdateSelectedDeposit(deposit);
Console.WriteLine(deposit.DepositAmount);
addTipView.TxtTipAmount = deposit.DepositAmount.ToString();
addTipView.TxtDate = deposit.DepoistDate.ToString();
addTipView.TxtHoursWorked = deposit.HoursWorked.ToString();
}
}
服务
public void UpdateSelectedDeposit(Deposit deposit)
{
repo.GetSelectedDeposit(deposit);
}
存储库
public void GetSelectedDeposit(Deposit deposit)
{
using (var context = new TipManagerDBEntities())
{
deposit = context.Deposits.Where(x => x.DepositID == deposit.DepositID).FirstOrDefault();
Console.WriteLine(deposit.DepositAmount);
}
}
当我在存储库中打印存款金额时,我得到了正确的值,但是当我在展示器中打印存款金额时,它是不正确的。我作为参数传递的存款 class 是通过引用传递的,对吧?为什么我的值在演示者中不正确。
当将 object 传递给方法(松散使用的术语)时,您实际上传递的是 reference ,但这里的重点是该对象的实际 reference 由 value 传递。意味着更新它(覆盖它)在 调用链 .
中没有任何作用如果您想覆盖 reference(通过 reference 传递 reference),那么您将需要使用 ref
关键字(在适当的地方)。
public void GetSelectedDeposit(ref Deposit deposit)