我在做家庭作业时遇到了麻烦,我们应该制作电话簿吗?条件是它应该看起来像这样:
Class Phonebook
{
private List<Entry> _phoneList;
public Phonebook()
{
//instance of _phoneList
}
public void AddEntry (string name, string number)
{
//logic
}
public string FindEntry (string namne)
{
//logic
}
}
class Entry
{
public string Name{ get; private set; }
public string Number{ get; private set; }
}
但是,我不确定如何使 AddEntry
方法将新名称/号码分配给条目列表 _phoneList
。我已经尝试了很多,但没有成功。有任何提示如何使其发挥作用吗?任何帮助将不胜感激!
到目前为止我的代码看起来像这样
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace app3
{
public partial class Form1 : Form
{
private Phonebook phonebook;
public Form1()
{
InitializeComponent();
phonebook = new Phonebook();
}
private void addEntryButton_Click(object sender, EventArgs e)
{
phonebook.AddEntry((addNameTextBox.Text), (addNumberTextBox.Text));
}
}
class Phonebook
{
private List<Entry> _phoneList;
public Phonebook()
{
List<Entry> _phoneList = new List<Entry>();
}
public void AddEntry(string name, string number)
{
}
}
class Entry
{
public string Name { get; private set; }
public string Number { get; private set; }
}
}
最佳答案
由于 _phoneList
是 Entry
的集合,因此您需要创建一个新实例并将其添加到列表中。
Entry entry = new Entry();
entry.Name = name;
entry.Number = number;
_phoneList.Add(entry);
但是,由于 Entry 具有属性的私有(private) setter ,因此您应该添加一个新的构造函数来接收名称和编号并将其设置在那里。
class Entry
{
public Entry(string name, string number)
{
Name = name;
Number = number;
}
public string Name { get; private set; }
public string Number { get; private set; }
}
然后它就会变成
_phoneList.Add(new Entry(name, number));
编辑:
private List<Entry> _phoneList;
public Phonebook()
{
List<Entry> _phoneList = new List<Entry>();
}
您将 _phoneList 声明为私有(private)字段,但随后在隐藏原始字段的构造函数中重新声明它。
当您稍后在 AddEntry 方法中使用 _phoneList
时,您将获得未初始化的字段。将构造函数更改为
_phoneList = new List<Entry>();
关于c# - 电话簿 - 进入类(class)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500039/