[英]List is getting initialized every time I call method
我是C#的新手。 我有一個包含兩個文本字段,一個按鈕和一個數據網格視圖的表單。 我正在嘗試將數據傳遞到業務邏輯層(BLL)並從那里傳遞到數據邏輯層(DAL),然后我將其添加到列表中並將列表返回到表單並顯示在數據網格視圖上。 問題是,每次添加新記錄時,以前的記錄都會消失。 看起來列表中的上一個條目被覆蓋。 我已經通過調試檢查了列表中的計數保持為1.謝謝
這是我如何從表單調用BLL方法在數據網格上顯示:
BLL_Customer bc = new BLL_Customer();
dgvCustomer.DataSource = bc.BLL_Record_Customer(cust);
這是BLL中的類
namespace BLL
{
public class BLL_Customer
{
public List<Customer> BLL_Record_Customer(Customer cr)
{
DAL_Customer dcust = new DAL_Customer();
List<Customer> clist = dcust.DAL_Record_Customer(cr);
return clist; // Reurning List
}
}
}
這是DAL中的類:
namespace DAL
{
public class DAL_Customer
{
List<Customer> clist = new List<Customer>();
public List<Customer> DAL_Record_Customer(Customer cr)
{
clist.Add(cr);
return clist;
}
}
}
每次嘗試添加新記錄時都要創建類實例。確保在任何類中只存在一個類的實例。在函數外部創建類的實例。
BLL_Customer bc = new BLL_Customer();
DAL_Customer dcust = new DAL_Customer();
這是發生了什么:
BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #1
dgvCustomer.DataSource = bc.BLL_Record_Customer(cust); // Does what you expect
再次調用此代碼時:
BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #2
舊列表和客戶信息存儲在BLL_Customer#1中。 參考bd
不再指向#1,而是指向#2。 要用代碼解釋這個,我可以這樣澄清:
var bd = new BLL_Customer().BLL_Record_Customer(cust); // A List<Customer>
bd = new BLL_Customer().BLL_Record_Customer(cust); // A new List<Customer>
附注:每次在應用程序中首次使用類DAL_Customer
時, List<Customer>
都會初始化為新值 - 在您的情況下是new List<Customer>()
。
如果您不以某種方式持久保存有關Customers
的信息,無論是文件,數據庫還是其他方式,每次加載應用程序時,您都會有一個新的List<Customer>
來應對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.