[英]C# How to add an item to List from another class
所以我正在尝试制作一个电话簿控制台应用程序。 一种选择是添加联系人。 问题是,一旦我向列表中添加了一个新项目并返回主菜单,然后使用 ViewAllContacts 选项,这个新项目就不会显示。 只是需要一些帮助来解决这个问题。 这是我的代码:
public class Contacts
{
public string ContactName { get; set; }
public int ContactNumber { get; set; }
public List<Contacts> listMethod()
{
List<Contacts> contacts = new List<Contacts>();
{
contacts.Add(new Contacts { ContactName = "John", ContactNumber = 1 });
contacts.Add(new Contacts { ContactName = "Jack", ContactNumber = 2 });
contacts.Add(new Contacts { ContactName = "Jay", ContactNumber = 3 });
}
return contacts;
}
然后我有另一个名为 AppOptions 的类,它有一些方法,如 SearchContact、ViewContact、ViewAllContacts 和 AddContact。 我将只显示 AddContact:
public void addContact()
{
Console.WriteLine(" Add Contact:");
Console.WriteLine(" ------------");
Console.WriteLine("Enter Name");
string newName = Console.ReadLine();
Console.WriteLine("Enter Number");
int newNumber = int.Parse(Console.ReadLine());
var b = contactobj.listMethod();
b.Add(new Contacts { ContactName = newName, ContactNumber = newNumber });
Console.WriteLine();
Console.WriteLine("Contact Saved");
Menu menuObj = new Menu();
menuObj.MenuMethod();
}
问题是你混合了一些概念。 您的联系人类包含“实体”联系人,还包含用于访问联系人实体的“存储库”模式。
当您调用 listMethod 方法时,您总是返回在该方法中创建的列表。 更好的近似可能是:
public class Contact
{
public string ContactName { get; set; }
public int ContactNumber { get; set; }
}
public class ContactManager
{
private List<Contact> Contacts {get; set; = new List<Contact>();
public List<Contacts> List() {
return Contacts;
}
public void Add(Conctact contact) {
Contacts.Add(contact);
}
public void Add(string name, int number) {
Contacts.Add(new Contact(name, number));
}
//Other access methods to the internal list
}
那么 AppOptions 类可以是:
class AppOptions
{
private ContactManager {get; set; } = new ContactManager();
public void addContact()
{
Console.WriteLine(" Add Contact:");
Console.WriteLine(" ------------");
Console.WriteLine("Enter Name");
string newName = Console.ReadLine();
Console.WriteLine("Enter Number");
int newNumber = int.Parse(Console.ReadLine());
ContactManager.Add(newName, newNumber);
Console.WriteLine();
Console.WriteLine("Contact Saved");
Menu menuObj = new Menu();
menuObj.MenuMethod();
}
}
这个想法是 ContactManager 为您提供对数据的访问。 在这种情况下,由于数据库中没有持久化数据,因此需要在内存中维护对 ContactManager 的引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.