由于访问级别保护,无法访问变量

时间:2012-05-22 01:24:20

标签: c#

我有以下课程:

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; }
}

我想从每个部门获得所有医生(部门班的Hashtable):

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'

2 个答案:

答案 0 :(得分:3)

您正在尝试遍历字典条目的Value字段,将其视为Doctor的集合。 docDic的迭代应该已经完成​​了您正在寻找的内容,只需要投射Value docDic的相应字段(可能是DictionaryEntry)。

Doctor doc = (Doctor) docDic.Value;

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

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

Doctor字段的类似更改)

然后你根本不需要上面的演员。

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

答案 1 :(得分: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; }
  }
 }