假设我有一个Employee类,其中一个属性是Department类型。在我的GUI中,我想创建一个新的Employee并实例化它。我有一个通过Department对象的ComboBox显示的集合,以便最终用户可以为每个Employee选择(分配)一个Department。
我的问题是,当我实例化这个Employee类并且我想将Department默认为某个值时,请说“Finance”是Department.Code属性。
我该怎么做?
我尝试了,但在保存时似乎并不喜欢:
this.Employee = Employee.CreateEmployee("-1", DateTime.Now, "Active", ...);
this.Employee.Department= new Department { Code = "Finance" };
非常感谢任何建议。
答案 0 :(得分:1)
通常,类是用构造函数构建的;即
public class Department
{
string _code = "";
public Department() {}
public Department(string code) {
_code = code;
}
}
因此,当您的程序创建新的部门对象时,您可以执行以下操作:
Department finance = new Department("Finance");
this.Employee = Employee.CreateEmployee("-1", DateTime.Now, "Active", ...);
this.Employee.Department= finance;
编辑:你可能最好使用枚举器,以便你可以声明一个枚举器:
public enum Departments
{
Finance,
Technology,
Sales
}
public class Employee
{
Departments _employeeDepartment;
public Employee() {}
public Employee(Department EmployeeDepartment)
{
_employeeDepartment = EmployeeDepartment;
}
}