通过调用方法只填充基类一次来填充基类属性?

时间:2017-07-20 11:41:49

标签: c#

我有以下3个班级:

public class Department
{
    public string Prop1 { get; set; }
    public string Prop2 { set; get; }
}

public class DeptCode100 : Department
{
    public string Prop3 { get; set; }
    public string Prop4 { set; get; }
}

public class DeptCode200 : Department
{
    public string Prop5 { get; set; }
    public string Prop6 { set; get; }
}

public class Employee
{
  public void Process()
  {
   foreach (var employee in _employees)
   {
      if (employee.deptCode == 100) // 100
      {
         var deptCode100 = new DeptCode100();
         InjectDepartment(deptCode100,employee);
      }
      else if (employee.deptCode == 200)//200
      {
         var deptCode200 = new DeptCode200();
         InjectDepartment(deptCode200,employee);
      }
   }
}
 protected void InjectDepartment(Department dept,Employee emp)
 {
     dept.Prop1 = emp.Code;
     dept.Prop2 = emp.Basic;
 }
}

现在我想做的是我只想调用一次这个InjectDepartment方法,而不是调用两次(因为稍后我将有3-4个子类,那么我将不得不根据子类的数量调用此方法4次并根据条件传递不同的子类。

2 个答案:

答案 0 :(得分:2)

我不确定这是不是你想要的,但我会试一试:

protected void InjectDetpartment(Department dept,Employee emp)
 {
     if(dept is DeptCode100 dc1)
     {
         dc1.Prop3 = emp.Code;
         dc1.Prop4 = emp.Basic;
     }
     else if(dept is DeptCode200 dc2)
     {
         dc2.Prop5 = emp.Code;
         dc2.Prop6 = emp.Basic;
     }
     else
     {
         dept.Prop1 = emp.Code;
         dept.Prop2 = emp.Basic;
     }
 }

答案 1 :(得分:2)

如果可能的话,只需使用构造函数初始化对象,这意味着它们在可用于调用代码的那一刻就完全形成了;并且使得初始化不可能在任何给定对象上发生两次:

public class Department
{
    public string Prop1 { get; set; }
    public string Prop2 { set; get; }

    public Department(string prop1, string prop2)
    {
        Prop1 = prop1;
        Prop2 = prop2;
    }
}

public class DeptCode100 : Department
{
    public string Prop3 { get; set; }
    public string Prop4 { set; get; }

    public DeptCode100(string prop1, string prop2, string prop3, string prop4) : base(prop1, prop2)
    {
        Prop3 = prop3;
        Prop4 = prop4;
    }
}

public class DeptCode200 : Department
{
    public string Prop5 { get; set; }
    public string Prop6 { set; get; }

    public DeptCode200(string prop1, string prop2, string prop5, string prop6) : base(prop1, prop2)
    {
        Prop5 = prop5;
        Prop6 = prop6;
    }
}

您不应该InjectDepartment,因为当您拥有创建它所需的一切时,您应该创建一个Department

// ...
if (employee.deptCode == 100)
{
    var dept1 = new Department100(employee.Code, employee.Basic, ...);
}

如果您在构建Prop3时确实不知道并且无法知道Department等的值,请将它们从子类构造函数中删除,并将其填入后面。