我創建了一個建構式 Employee(string id, string firstname, string lastname, string roleid) 并添加了一個類別庫作為業務邏輯和一個控制臺應用程式來運行程式。我想要做的是在員工串列中添加和查看元素。
//Logic
public class Domain
{
public List<Employee> Employees { get; set; } = new List<Employee>();
public void AddEmployee(Employee employee)
{
Employees.Add(employee);
}
public List<Employee> GetAllEmployee()
{
return Employees;
}
}
在控制臺應用程式中,我為此創建了一個程式,但不是添加到串列中,而是將新元素添加到我創建的實體中。
//Console App
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("PPM Project");
Console.WriteLine("1 Add employee");
Console.WriteLine("2 View Employee");
var userInput = Console.ReadLine();
var business1 = new Domain();
var allemployee = business1.GetAllEmployee();
while (true)
{
switch (userInput)
{
case "1":
Console.WriteLine("adding employee first name:");
var FName = Console.ReadLine();
Console.WriteLine("adding employee last name:");
var LName = Console.ReadLine();
Console.WriteLine("adding 3digit Role Id:");
var RoleId = Console.ReadLine();
Console.WriteLine("adding 4digit Employee Id:");
var EmpId = Console.ReadLine();
var newEmployee = new Employee(EmpId, FName, LName, RoleId);
business1.AddEmployee(newEmployee);
break;
case "2":
foreach (var employee in allemployee)
{
Console.WriteLine($"Employee: {employee.EmpId}\t {employee.FName} {employee.LName}, is assigned a RoleID : {employee.RoleId}");
}
break;
default:
Console.WriteLine("Select");
break;
}
Console.WriteLine("Select option");
userInput = Console.ReadLine();
}
}
}
代碼運行正確,我可以添加和查看員工和專案,但專案或員工都沒有添加到我在業務邏輯中宣告的串列專案和員工中,而是在我創建的新實體中使用。如何在串列中添加元素以及我應該修改哪部分代碼?
uj5u.com熱心網友回復:
您正在適當地添加新Employee的類實體Domain.Employees,實際問題是您的第二種switch情況。
以防2萬一,您正在迭代allemployee在開始時獲取的內容,而不是每次用戶2作為選項輸入時都獲取所有員工。
這樣,您將allemployee在每次通話中將最新的員工記錄存盤在變數中。
public static class Program
{
public static void Main(string[] args)
{
//Your existing code goes here
//var allemployee = business1.GetAllEmployee(); //Don't call it here
while (true)
{
switch (userInput)
{
case "1":
//Your existing code goes here
break;
case "2":
var allemployee = business1.GetAllEmployee(); //Call GetAllEmployee inside case 2 not on top
foreach (var employee in allemployee)
{
Console.WriteLine($"Employee: {employee.EmpId}\t {employee.FName} {employee.LName}, is assigned a RoleID : {employee.RoleId}");
}
break;
//Your existing code goes here
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425606.html
上一篇:計算子串列中5個值中前4個int值的平均值。(2個值相同)
下一篇:如何從多維陣列計算最大精度?
