对象EmployeeInfoDocument包含一个组列表。每个小组都有一份员工清单。我试图使用嵌套的foreach循环将值写入XML文件。似乎我在内部foreach循环中有错误的语法。 Visual Studio给出了以下错误:
foreach语句不能对类型' InfoObjects.Group'的变量进行操作。因为' InfoObjects.Group'不包含' GetEnumerator'
的公开定义如何从群组中的每位员工提取信息?我对C#非常陌生。
任何见解都将受到赞赏。
namespace InfoObjects
{
public class EmployeeInfoDocument
{
private List<Group> _groups = new List<Group>();
public List<Group> Groups
{
get { return _groups; }
set { _groups = value; }
}
}
public class Group
{
private string _text = string.Empty;
private List<Employee> _info = new List<Employee>
public Group()
{
}
public string Text
{
get {return _text; }
set { _text = value; }
}
public List<Employee> Employees
{
get { return _info }
set { _info = value; }
}
}
public class Employee
{
private string _name = string.Empty;
private string _department = string.Empty;
public Employee()
{
}
public string Name
{
get { return _name;}
set { _name = value;}
}
{
public string Department
{
get { return _department};
set { _department = value;}
}
}
}
namespace UI
{
public partial class Mainform: Form
{
private void OnSave(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.RestoreDirectory = false;
saveFileDialog.InitialDirectory = Assembly.GetExecutingAssembly().Location;
saveFileDialog.Filter = "Employee Files|*.xml";
saveFileDialog.DefaultExt = "xml";
using (saveFileDialog)
{
if (saveFileDialog.ShowDialog(this) != DialogResult.OK)
return;
}
using (XmlWriter xmlw = XmlWriter.Create(saveFileDialog.FileName))
{
EmployeeInfoDocument k = new EmployeeInfoDocument();
List<Group> myList = k.Groups;
xmlw.WriteStartDocument();
xmlw.WriteStartElement("EmployeeInfo");
foreach (Group group in EmployeeInfoMgr.Document.Groups)
{
xmlw.WriteStartElement("Group Name");
xmlw.WriteString(group.Text);
foreach (Employee employee in group)
{
xmlw.WriteStartElement("Employee Name");
xmlw.WriteString(employee.Name);
xmlw.WriteEndElement();
xmlw.WriteStartElement("Employee Department");
xmlw.WriteString(employee.Department);
xmlw.WriteEndElement();
}
xmlw.WriteEndElement();
}
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
}
}
}
}
再次感谢。我已经被困在这几个小时了。
编辑:缺少半冒号(非常抱歉!)
答案 0 :(得分:2)
所以这是你的问题:
foreach (Group group in ...)
{
...
foreach (Employee employee in group)
{
}
}
编译器无法使用foreach
而不是group
因为它不知道你要迭代什么。您需要实现IEnumerable<T>
(或至少提供适当的GetEnumerator()
方法)或指定您实际想要迭代组中的员工:
foreach (Employee employee in group.Employees)
当然,后者不是一个变化,但是如果你希望能够遍历一个组,你就可以像这样实现它:
public class Group : IEnumerable<Employee>
{
public string Text { get; set; }
public List<Employee> Employees { get; set; }
public IEnumerator<Employee> GetEnumerator()
{
return Employees.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
注意:
IEnumerable<T>
时,您还需要实现非通用IEnumerable
,我已使用显式接口实现,因为GetEnumerator
方法与{IEnumerable<T>
方法中的方法冲突1}}。Add(Employee)
方法或任何您需要的方法。