我正在做一个学校项目。用户可以输入 Persons 对象并将它们存储在 Person 类型的 List 中。它工作正常,期望当我从另一个类调用列表时,列表是空的!
class SubMenu
{
CreatePersons cp;
List<Person> myList = new List<Person>();
public List<Person> MyList
{
get { return myList; }
}
string UserInput= null;
public void SMenu()
{
Boolean flag = true;
while (true)
{
Console.WriteLine("");
Console.WriteLine(" -------------------------------------------");
Console.WriteLine(" -|---------------------------------------|-");
Console.WriteLine(" -|- P. Create a Person -|-");
Console.WriteLine(" -|- S. Create a Student -|-");
Console.WriteLine(" -|- T. Create a Teacher -|-");
Console.WriteLine(" -|- A. Create Administrative Staff -|-");
Console.WriteLine(" -|- R. Return to Main Menu -|-");
Console.WriteLine(" -|---------------------------------------|-");
Console.WriteLine(" -------------------------------------------");
Console.Write(" Enter your choice: ");
UserInput = Console.ReadLine();
switch (UserInput.ToLower())
{
case "p": myList.Add(new Person("Johnny")); //For testing
Console.WriteLine(myList.Count); //For testing .. here count = 1 as it should be.
break;
case "s": Console.WriteLine("Creates and object of type Student.");
break;
这是用户创建新人员的类。我创建了一个 Person 进行测试。问题是当我从另一个类调用列表时,列表是空的,它应该有一个同伴!这是另一个类的代码。
class MainMenu
{
Boolean flag = true;
SubMenu sm = new SubMenu();
public void MMenu()
{
while (true)
{
Console.WriteLine();
Console.WriteLine("Console Application v1.0 created by");
Console.WriteLine();
Console.WriteLine(" ---------------------------------------------------");
Console.WriteLine(" -|-------------- MENU ---------------------------|-");
Console.WriteLine(" -|-----------------------------------------------|-");
Console.WriteLine(" -|- 1 - Create a Person -|-");
Console.WriteLine(" -|- 2 - List all the Persons -|-");
Console.WriteLine(" -|- 3 - Search for a Person -|-");
Console.WriteLine(" -|- 4 - Display the number of Persons -|-");
Console.WriteLine(" -|- 5 - Exit -|-");
Console.WriteLine(" ---------------------------------------------------");
Console.Write(" Enter your choice: ");
string UserInput = Console.ReadLine();
Console.WriteLine();
int input;
if (int.TryParse(UserInput, out input))
{
switch (input)
{
case 1:Console.WriteLine("Case 1");
sm.SMenu();
break;
case 2:Console.WriteLine("Case 2"); //This should display the one, the current size of the List.
int size = sm.MyList.Count;
Console.WriteLine("Size :" + size);
break;
case 3: Console.WriteLine("Case 3");
请查看评论,以便可以轻松识别问题。
谢谢你的帮助。