0

我正在创建一个 XML,如下面的代码所示

public class Group
{
[XmlElement(typeof(Manager))]
public Employee [] Staff;

[XmlElement (typeof(int)),
XmlElement (typeof(string)),
XmlElement (typeof(DateTime))]
public ArrayList ExtraInfo;
}

public class Employee
{
public string Name;
}

public class Manager:Employee
{
public int Level;
}

public class Run 
{
public static void Main()
{
  Run test = new Run();
  test.SerializeObject("TypeEx.xml");
}

public void SerializeObject(string filename)
{
     // Create an XmlSerializer instance.
  XmlSerializer xSer = 
  new XmlSerializer(typeof(Group));

  // Create object and serialize it.
  Group myGroup = new Group();

  Manager e1 = new Manager();
  e1.Name = "Manager1";
  Manager m1 =  new Manager();
  m1.Name = "Manager2";
  m1.Level = 4;

  Employee[] emps = {e1, m1};
  myGroup.Staff = emps;

  myGroup.ExtraInfo = new ArrayList();
  myGroup.ExtraInfo.Add(".NET");
  myGroup.ExtraInfo.Add(42);
  myGroup.ExtraInfo.Add(new DateTime(2001,1,1));

  TextWriter writer = new StreamWriter(filename);
  xSer.Serialize(writer, myGroup);
  writer.Close();
  }
  } 

在“ http://msdn.microsoft.com/en-IN/library/system.xml.serialization.xmlelementattribute.type(v=vs.80).aspx ”上共享。在这种情况下,我在员工中添加了 2 个经理,分别是“e1”和“m1”。但是如果我必须在一个循环中添加 5 个管理器,我将这段代码更新如下: Manager[] a = new Manager[5];

    for (int i = 0; i < 5; i++)
    {
        a[i] = new Manager();
        a[i].Name = "temp" + i;
        a[i].Level = i;
    }
    Employee[] empss = new Employee[5];

    for (int k = 0; k < 5; k++)
    {
        empss[k] = new Employee();
        myGroup.Staff = empss[k]; // line25
    } 

但它给了我以下错误:“无法将类型'Employee'隐式转换为'Employee []'”在第25行。有人可以建议我如何纠正它吗?

4

0 回答 0