由于访问级别保护,无法访问变量
本文关键字:访问 变量 访问级别 保护 | 更新日期: 2023-09-27 18:34:49
我有以下类:
class Department
{
private string departmentId;
private string departmentName;
private Hashtable doctors = new Hashtable();//Store doctors for
//each department
public Hashtable Doctor
{
get { return doctors; }
}
}
我有一个包含部门对象的数组列表:
private static ArrayList deptList = new ArrayList();
public ArrayList Dept
{
get { return deptList; }
}
我正在尝试从每个部门获取所有医生(部门类中的哈希表(:
foreach (Department department in deptList)
{
foreach (DictionaryEntry docDic in department.Doctor)
{
foreach (Doctor doc in docDic.Value)//this is where I gets an error
{
if (doc.ID.Equals(docID))//find the doctor specified
{
}
}
}
}
但是我无法编译该程序。它给出一个错误:
foreach statement cannot operate on variables of type 'object' because
'object' does not contain a public definition for 'GetEnumerator'
您正在尝试遍历字典条目的Value
字段,将其视为Doctor
集合。 docDic
的迭代应该已经完成了您正在寻找的操作,只需要投射docDic
DictionaryEntry
的适当字段(可能Value
Doctor doc = (Doctor) docDic.Value;
更好的是,您可以使用泛型并在声明映射时表示字典键/值的类型:
private Hashtable<string, Doctor> doctors = new Hashtable<string, Doctor>();
(Doctor
字段的类似更改(
那么你根本不需要上面的演员表。
注意:我假设您正在从医生的 id(键(映射到Doctor
对象(值(,并且 id 是一个字符串
在
类前面加上公共访问修饰符
public class Department
{
private string departmentId;
private string departmentName;
private Hashtable doctors = new Hashtable();//Store doctors for
//each department
public Hashtable Doctor
{
get { return doctors; }
}
}