0

我有以下课程:

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'
4

2 回答 2

3

您正在尝试遍历字典条目的Value字段,将其视为Doctors 的集合。的迭代docDic应该已经完成​​了您正在寻找的事情,只需要Value转换docDic DictionaryEntry.

Doctor doc = (Doctor) docDic.Value;

更好的是,您可以使用泛型并在地图声明时表示字典键/值的类型:

private Hashtable<string, Doctor> doctors = new Hashtable<string, Doctor>();

(该Doctor领域的类似变化)

那么你根本不需要上面的铸件。

注意:我假设您正在从医生的 id(键)映射到Doctor对象(值),并且 id 是一个字符串

于 2012-05-22T01:29:59.700 回答
1

使用公共访问修饰符为您的课程添加前缀

 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; }
  }
 }
于 2012-05-22T01:33:38.283 回答