C# 通过调用方法只填充一次基类来填充基类属性?
我有以下三门课:C# 通过调用方法只填充一次基类来填充基类属性?,c#,C#,我有以下三门课: 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 Dept
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次),并根据条件传递不同的子类。我不确定这是否是您想要的,但我会尝试一下:
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;
}
}
如果可能的话,只需使用构造函数初始化对象,这意味着它们在可用于调用代码的那一刻就已完全成形;使初始化不可能在任何给定对象上发生两次:
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
,因为当您拥有创建部门所需的一切时,您应该创建一个部门
:
// ...
if (employee.deptCode == 100)
{
var dept1 = new Department100(employee.Code, employee.Basic, ...);
}
如果您在构建部门时确实不知道或无法知道
Prop3
等的值,请将这些值从子类构造函数中删除,以后再填写。您不会在提供的代码中调用它。请添加您正在谈论的代码使用构造函数注入?InjectionDepartment方法属于哪个类?@RomanoZumbé更新了我的codeWell,但它是无效代码,因为您在类声明中直接有一个foreach
循环。。。请对您为帮助我所做的努力表示感谢,但请注意,部门的Prop1和Prop2正在从员工身上获得价值,即emp.代码和emp。Basic@Learning:因此,在调用构造函数时,请传入这些值。或者更好的是,将构造函数更改为接受Employee
,然后从那里填充它们…@Learning-我添加了一个使用示例。传递员工
也是一个好主意,除非您出于某种原因不希望这种耦合。非常感谢您的回答,请继续这样帮助。感谢:)