我正在做一个小程序,只是为了进一步学习xml序列化,我保存了属于名为Person的对象的id,name,age。但不知何故,它会引发异常(由于其保护级别,xmlTeste.Person无法访问。只能处理公共类型。)。我该如何改进我的代码?预期的结果是使用对象Person创建的xml文件。
对象人物:
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);
}
答案 0 :(得分:4)
Person
是一个内部类。这是异常所说的“保护级别”。在C#中,如果未明确指定保护级别,则internal
是默认值。
只能处理公共类型
如果它只能处理公共类型,并且您希望它处理您的类型,请尝试将您的类型设为公开类型。序列化代码无法对您的类执行任何操作,因为序列化代码无法访问您的类 - 内部意味着在其自己的程序集之外的任何人都无法访问它。
像这样定义你的类:
public class Person {
...