假设任何政府办公室都有一类部门(由部门类代表),并且有一类工人(由工人阶级代表)。 这个代码结构是否正确?
class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
class Worker
{
public int WorkerId { get; set; }
public string WorkerName { get; set; }
private Department dept = new Department();
public Department Dept
{
get
{
return dept;
}
set
{
dept.DepartmentId = value.DepartmentId;
dept.DepartmentName = value.DepartmentName;
}
}
}
答案 0 :(得分:7)
这种形式的代码是否正确?
不,因为从呼叫者的角度来看,它有意想不到的行为。 Department
是一个类,即引用类型;因此,当您将Department
的实例分配给类型为Department
的属性时,您希望在阅读该属性时获得相同的实例。但在您的情况下,您只需将属性复制到另一个实例...通常,使用引用类型,如果您这样做,则需要:
Department d = new Department();
worker.Department = d;
d.DepartmentName = "Foo";
然后worker.Department.DepartmentName
也将是" Foo"。但是你的代码并不正确,这对调用者来说是令人惊讶的;你应该尽可能地避免意外,因为它是错误的来源。
此外,它不易维护,因为如果向Department
添加更多属性,则必须更新属性的代码。
答案 1 :(得分:0)
正如Thomas指出的那样,Worker类应该对Department类的内部属性一无所知。事实上,因为ID&名称将绑在一起,它们不应该是可更改的。
class Department
{
public int DepartmentId { get; private set; }
public string DepartmentName { get; private set; }
public Department(int id, string name)
{
DepartmentId = id;
DepartmentName = name;
}
}
因此,一旦你创建了一个Department对象,它将始终具有该名称& ID。同一部门中的所有Worder都可以共享同一个对象:
class Worker
{
public int WorkerId { get; set; }
public string WorkerName { get; set; }
public Department Dept {get; set;}
}
答案 2 :(得分:0)
那可能没问题。我喜欢这样做我的课程:
class Department
{
public Department() {}
public Department(int departmentId, string departmentName)
{
DepartmentId = departmentId;
DepartmentName = departmentName;
}
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
class Worker
{
public Worker() {}
public Worker(int workerId, string workerName, Department department)
{
WorkerId = workerId;
WorkerName = workerName;
Dept = department;
}
public Worker(int workerId, string workerName, int departmentId, string departmentName)
: this(workerId, workerName, new Department(departmentId, departmentName)) {}
public int WorkerId { get; set; }
public string WorkerName { get; set; }
public Department Dept { get; set; }
}
在我看来,这给了你最大的灵活性。除非您立即对类中的对象执行某些操作(计算等),否则我不希望在内部实例化它们,而只是通过构造函数或公共属性进行赋值,因此您始终知道其中的内容。只需确保您将在部门执行操作的任何地方,检查以确保它不为空。