2016-12-23 4 views
-1

Я разрабатываю программу, которая позволяет добавлять, редактировать и т. Д. Сотрудников. Я застрял в части предоставления Работнику отдела (Департамент - класс), который мне нужно создать на основе его имени. Любая помощь?Создание объекта на основе строки

Код:

Департамент класса

class Department 
{ 
    public Department() { } 

    public int DepartmentId { get; set; } 
    public string DepartmentName { get; set; } 
    public string Location { get; set; } 

    public ICollection<Employee> EmployeesAtDepartment { get; set; } 
} 

Класс Employee

abstract class Employee 
{ 
    public int EmployeeId { get; set; } 
    public string EmployeeName { get; set; } 
    public string EmployeeSurname { get; set; } 
    public string Address { get; set; } 
    public int Grade { get; set; } 
    public double Salary { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 

    public Department DepartmentOfEmployee {get; set; } 

Метод сбора данных

public Employee EmpDetails(Employee NewEmp) 
{ 
    Console.WriteLine("Enter Employee Name:"); 
    NewEmp.EmployeeName = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Surname:"); 
    NewEmp.EmployeeSurname = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Address:"); 
    NewEmp.Address = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Grade:"); 
    NewEmp.Grade = Convert.ToInt16(Console.ReadLine()); 
    Console.WriteLine("Enter Employee Salary:"); 
    NewEmp.Salary = Convert.ToDouble(Console.ReadLine()); 
    Console.WriteLine("Enter Department of Employee:"); 
    NewEmp.DepartmentOfEmployee = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Username:"); 
    NewEmp.Username = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Password:"); 
    NewEmp.Password = Console.ReadLine(); 

    return NewEmp; 
} 
+1

Это поможет, если вы указали нам определение «Сотрудник», «Департамент» и где/как вы храните список отделов, которые мы можем найти, когда пользователь набирает что-то (и как это что-то связано с де partment) – Jamiec

+0

Просто создайте экземпляр класса Департамента и заполните его. –

+0

У вас есть список отделов на какой-то БД? или вы просто хотите добавить новый отдел каждый раз, когда вы добавляете сотрудника? – Stephen

ответ

2

Вы просто не можете напрямую конвертировать строку т o экземпляр класса. Однако вы могли бы достичь что-то подобное с помощью Factory Pattern:

public static class DepartmentFactory 
{ 
    public static Department CreateDepartment(string deptStr) 
    { 
     var dept = new Department(); 
     // rest of the code 

     return dept; 
    } 
} 

И новый код:

public Employee EmpDetails(Employee NewEmp) 
{ 
    Console.WriteLine("Enter Employee Name:"); 
    NewEmp.EmployeeName = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Surname:"); 
    NewEmp.EmployeeSurname = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Address:"); 
    NewEmp.Address = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Grade:"); 
    NewEmp.Grade = Convert.ToInt16(Console.ReadLine()); 
    Console.WriteLine("Enter Employee Salary:"); 
    NewEmp.Salary = Convert.ToDouble(Console.ReadLine()); 
    // Edit here 
    Console.WriteLine("Enter Department of Employee:"); 
    NewEmp.DepartmentOfEmployee = DepartmentFactory.CreateDepartment(Console.ReadLine()); 
    Console.WriteLine("Enter Employee Username:"); 
    NewEmp.Username = Console.ReadLine(); 
    Console.WriteLine("Enter Employee Password:"); 
    NewEmp.Password = Console.ReadLine(); 

    return NewEmp; 
} 
0

держать вещи аккуратные здесь просто использовать перечисление и передать в текстовое значение, как показано ниже:

public class Employee 
    { 
     public string Name { get; private set; } 

     public AvailableClasses Class { get; private set; } 

     public Employee(string name, string myClass) 
     { 
      Name = name; 
      AvailableClasses classEnum; 
      if (!Enum.TryParse(myClass, true, out classEnum)) 
       classEnum = AvailableClasses.Other; 

      Class = classEnum; 
     } 
    } 

    public enum AvailableClasses 
    { 
     Maths, 
     Science, 
     Other 
    }