每次调用方法时,List都会被初始化

时间:2013-09-02 00:24:16

标签: c#

我是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;
         }
     }
 }

2 个答案:

答案 0 :(得分:2)

每次尝试添加新记录时都在创建类实例。确保在任何类中只存在一个类的实例。在函数外部创建类的实例。

BLL_Customer bc = new BLL_Customer();


DAL_Customer dcust = new DAL_Customer();

答案 1 :(得分:0)

以下是发生的事情:

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>到满意于。

相关问题