【发布时间】:2016-06-28 16:49:23
【问题描述】:
我正在做一个小程序,只是为了进一步学习 xml 序列化,我保存了属于名为 Person 的对象的 id、name、age。但不知何故,它抛出了一个异常( xmlTeste.Person 由于其保护级别而无法访问。只能处理公共类型。)。我怎样才能改进我的代码?预期的结果是使用对象 Person 创建一个 xml 文件。
对象Person:
class Person
{
#region Variables
private int id = 0;
private string name = string.Empty;
private int idade = 0; //it's age in portuguese
#endregion
#region Properties
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Idade //again... means age
{
get { return idade; }
set { idade = value; }
}
#endregion
}
我的班级管理 xml 序列化
class XMLController
{
private static void SerializeAndSaveObject(XmlSerializer writer, Person item)
{
var path = "C://Folder//teste.xml";
FileStream file = File.Create(path);
writer.Serialize(file, item);
file.Close();
}
public static void SaveFile(Person person)
{
SerializeAndSaveObject(new XmlSerializer(typeof(Person)), pessoa);//here is where i am having the error
//An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
//Additional information: xmlTeste.Pessoa is inaccessible due to its protection level. Only public types can be processed.
}
}
用法:
private void btnGo_Click(object sender, EventArgs e)
{
Person p = new Person
{
Id = 2,
Name = "DEFEF",
Idade = 2 //means age
};
xmlTeste.XMLController.SaveFile(p);
}
【问题讨论】: