0
我是c#中的一個begginer。 我的問題是,我想創建一個對象列表,我可以動態地添加對象,然後打印他們的屬性(我想去我想要的每個對象,只打印他的屬性)。 我環顧了網絡,並沒有找到一個好的答案,這將幫助我理解如何正確地做到這一點。 我加了一個try ... catch來理解問題,但是我得到的解釋是我沒有添加實例來打印他的屬性,即使我總是這樣做了。如何在列表中打印對象的屬性?
我真的失去了,所以任何幫助,將不勝感激。
我的代碼:
類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using APPcLASS_2;
using System.Collections;
namespace EmployeesBooks
{
public class EMpLOYcLaSS
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PhoneNumber { get; set; }
public string Adress { get; set; }
public int Days { get; set; }
public int Mounths { get; set; }
public int Years { get; set; }
}
}
主程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using APPcLASS_2;
using EmployeesBooks;
namespace EmployeesBooks
{
class Program
{
static void Main(string[] args)
{
EMpLOYcLaSS Employ = new EMpLOYcLaSS();
List<EMpLOYcLaSS> ListOfObjects = new List<EMpLOYcLaSS>();
string FirstNameVar, LastNameVar, AdressVar;
int PhoneNumberVar, DayVar, MounthVar, YearVar;
while(true)
{
Console.Clear();
Console.WriteLine("Enter your choise:");
Console.WriteLine("1-Add an employee");
Console.WriteLine("2-Earase employee");
Console.WriteLine("3-Show reports");
var choise=int.Parse(Console.ReadLine());
switch(choise)
{
case 1:
Console.WriteLine("Enter First Name:",Employ.FirstName);
FirstNameVar = Console.ReadLine();
Employ.FirstName = FirstNameVar;
Console.WriteLine("Enter Last Name:");
LastNameVar = Console.ReadLine();
Employ.LastName = LastNameVar;
Console.WriteLine("Enter Phone Number:");
PhoneNumberVar =int.Parse(Console.ReadLine());
Employ.PhoneNumber = PhoneNumberVar;
Console.WriteLine("Enter Address:");
AdressVar = Console.ReadLine();
Employ.Adress = AdressVar;
Console.WriteLine("Enter Birthday:");
Console.WriteLine("Day:");
DayVar =int.Parse(Console.ReadLine());
Employ.Days = DayVar;
Console.WriteLine("Mounth:");
MounthVar = int.Parse(Console.ReadLine());
Employ.Mounths = MounthVar;
Console.WriteLine("Year:");
YearVar = int.Parse(Console.ReadLine());
Employ.Years = YearVar;
ListOfObjects.Add(new EMpLOYcLaSS());
break;
case 3:
try
{
Console.WriteLine("enter a number of employee:(1,2,3,4...)");
var EmployeeNumberForPrinting = int.Parse(Console.ReadLine());
if (ListOfObjects[EmployeeNumberForPrinting] != null)
Console.WriteLine("{0}", ListOfObjects[EmployeeNumberForPrinting].FirstName.ToString());
else
Console.WriteLine("Don't Exist!");
Console.WriteLine("Press any key to proceed");
Console.ReadKey();
break;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
break;
}
}
}
}
}
}