我想将List分配给成员变量(变量是List),但我总是收到错误消息:System.StackOverflowException
未处理,我不知道原因,请参阅下面的代码:< / p>
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int DeptID { get; set; }
}
public class Department
{
public int DeptID { get; set; }
public string DeptName { get; set; }
public List<Employee> Employees
{
set { Employees = value; }
//get { return EmployeeDataAccessLayer.getEmployeesByDeptID(DeptID); }
get { return Employees; }
}
}
public class EmployeeDataAccessLayer
{
public static List<Employee> getEmployeesByDeptID(int deptID)
{
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlStr = "select * from tblemployee where deptid = :deptid order by employeeid asc";
List<Employee> employees = new List<Employee>();
using (OracleConnection ocon = new OracleConnection(conStr))
{
OracleCommand ocmd = new OracleCommand(sqlStr, ocon);
ocmd.Parameters.Add(":deptid", deptID);
ocmd.Connection.Open();
OracleDataReader rdr = ocmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.EmployeeID = Convert.ToInt32(rdr["EMPLOYEEID"]);
employee.EmployeeName = rdr["NAME"].ToString();
employee.DeptID = Convert.ToInt32(rdr["DEPTID"]);
employees.Add(employee);
}
}
return employees;
}
}
public class DepartmentDataAccessLayer
{
public static List<Department> getAllDepartments()
{
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlStr = "select * from tbldepartment order by departmentid asc";
List<Department> depts = new List<Department>();
using (OracleConnection ocon = new OracleConnection(conStr))
{
OracleCommand ocmd = new OracleCommand(sqlStr, ocon);
ocmd.Connection.Open();
OracleDataReader rdr = ocmd.ExecuteReader();
while (rdr.Read())
{
Department dept = new Department();
dept.DeptID = Convert.ToInt32(rdr["DEPARTMENTID"]);
dept.DeptName = rdr["NAME"].ToString();
dept.Employees = EmployeeDataAccessLayer.getEmployeesByDeptID(dept.DeptID);
depts.Add(dept);
}
}
return depts;
}
}
所以,我调试它,发现异常发生在:
set { Employees = value;}
见下面的截图:
我真的不知道为什么,你能告诉我原因还是给我一些建议?
答案 0 :(得分:2)
在你的情况下,当你为Employees
分配一些东西时,它的setter会再次触发它分配给同一个变量,所以同样的过程会继续进行,这会导致无限分配,这就是你得到那个异常的原因。克服这个改变这样的属性定义:
private List<Employee> _Employees
public List<Employee> Employees
{
set { _Employees = value; }
get { return _Employees; }
}
或者像这样:
public List<Employee> Employees { get; set; }
答案 1 :(得分:1)
如果您使用get和set在C#中设置值,那么您需要做的只是
public List<Employee> Employees{get; set;}
使用空的get和set块,将自动分配该值。在你的代码中,你实际上一遍又一遍地调用你的变量的set函数,直到发生StackOverflow异常
有关属性here
的更多信息答案 2 :(得分:1)
因为您将Employees
设置为value
,将Employees
设置为value
,将Employees
设置为value
即设置public List<Employee> Employees { get; set; }
.......等等,直到堆栈溢出。
因为您没有使用私有变量来保存员工,所以您可以使用auto-getter和-setter将值设置为自身,就像其他属性一样:
private List<Employee> _employees;
public List<Employee> Employees
{
set { _employees = value; }
get { return _employees; }
}
否则,设置一个私有变量来保存员工列表。这可以使用
{{1}}