【问题标题】:Issue with protection level when serializing序列化时的保护级别问题
【发布时间】: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);


    }

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    Person 是一个内部类。这就是异常所说的“保护级别”。在 C# 中,internal 是默认值,如果您没有明确指定保护级别。

    只能处理公共类型

    如果它只能处理公共类型,并且您希望它处理您的类型,请尝试将您的类型设为公共。序列化代码无法对您的类执行任何操作,因为序列化代码无权访问您的类 - 内部意味着它自己的程序集之外的任何人都无法访问它。

    像这样定义你的类:

    public class Person {
    ...
    

    【讨论】:

    • 我花了几个小时寻找错误,它是如此明显......感谢您指出这一点!
    • @AlexeiLevenkov 更新,tx
    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2017-04-13
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多