我有一个关于在两个窗体之间维护List的查询。这是我需要创建地址簿的项目。
我选择以列表的形式维护联系人详细信息。我的第一个窗体(form1)包含列表AddressBook
的主副本,其中包含地址簿。
我将4个条目硬编码到地址簿列表中,以便进行实验并获得简单的功能,例如“添加”和“编辑”工作。
我有第二个名为Add的窗体,我可以在其中添加新条目到列表中。这很好用。我可以在ADD表单中添加一个新联系人,它显示在初始form1,主表单中。
我的问题出现在编辑表格中。我将AddressBook(主)列表传递给EDIT表单。 EDIT表单获取主列表,我可以操作该列表中的记录。但是,当将新列表发送回母版页(form1)时,它不会将其拾取。我使用与ADD表单中相同的代码,该表单成功发送回新列表。但是,在发回已编辑的列表时,此代码不起作用。
这是我在form1
中的AddressBook属性public List<Contact> addressBook;
public List<Contact> AddressBook
{
get { return addressBook;}
set {addressBook = value;}
}
在EDIT中:
public Edit()
{
InitializeComponent();
temp = Master.AddressBook; // temp is the temporary List I update within EDIT
}
**然后我有我的算法成功地让我编辑列表临时。列表temp现在具有已编辑的列表* *
然后当我点击保存按钮时,我使用以下代码;
Master.AddressBook = temp;
我需要的只是将列表temp发送回form1。
代码Master.AddressBook = temp;
通过ADD表单向列表添加值时的工作原理。
添加表格:
public Add()
{
InitializeComponent();
temp = Master.AddressBook;
}
**** code to add a new record into the list temp. the new record is called newRecord**********
private void btnAddClose_Click(object sender, EventArgs e)
{
stor.AddressBook = temp; // when I hit close on the form, it updates the master list AddressBook
this.Close();
}
这可能是非常糟糕的措辞,但实质上我的代码失败的唯一一点是当我想在form1中更改我的主要Addressbook时,将其替换为list temp,这是我的EDIT表单中的编辑列表。
我认为这与我的AddressBook属性有关。但这并不能解释为什么我可以用包含新记录的列表替换AddressBook,但我不能用包含已编辑记录的列表替换它。
答案 0 :(得分:2)
实现此目的的一种方法是使主列表中的列表静态。
站长:
public static List<Contact> AddressBook { get; set; }
注意:您不需要支持变量,如果您确实想要使用它,最佳实践会建议它是私有的。如果您决定使用它,它也需要是静态的。
在Add表单中,您将收集数据以创建新的Contact对象,而temp实际上应该只是一个Contact对象。 添加表格:
private Contact newRecord = null;
public Add()
{
InitializeComponent();
newRecord = new Contact();
}
/**** code to add the user-input to the new Contact object ****/
private void btnAddClose_Click(object sender, EventArgs e)
{
Master.AddressBook.Add(newRecord);
this.Close();
}
希望这有帮助。
答案 1 :(得分:0)
这就是Singleton
模式派上用场的地方:Implementing Singleton in C#
您会注意到应用程序设置使用相同的patttern来允许您全局访问它而无需传递它。
当我使用Singleton
时,我通常会将类名称设为(TypeName)Manager (例如: AddressBookManager )。
所以课程可能是这样的:
public static class AddressBookManager
{
#region Singleton
static readonly AddressBookManager instance = new AddressBookManager();
private AddressBookManager(); // prevent creating instances of this
public static AddressBookManager Current { get { return instance; } }
#endregion
AddressBook master = new AddressBook(); // the master address book
public AddressBook Master
{
get { return master; } // get the master address book
set { master = value; } // set the master address book
}
}
然后在每种形式中你都会这样访问它:
var addressBook = AddressBookManager.Current.Master;
addressBook.Add(newRecord);
使用编辑功能遇到的问题可能与您使用临时列表的方式有关。通过使用静态的全局列表并仅添加/编辑其中的项目,您不会运行该问题。由于您的Contact
项目是class
(不是struct
),因此它们的更改将自动反映在列表中,因为它们是引用类型。
关于Singleton
类的重要部分是能够从项目的任何位置访问它们。唯一需要注意的是,在使用多线程应用程序和Singleton
类时,您需要格外小心。