公共类 - “无法访问由于其保护级别。 只有公共类型可以处理“。(Public Class -

2019-07-30 04:34发布

我做的一个测试项目,了解对象的XML序列化,和我得到一个奇怪的运行时错误:

namespace SerializeTest
{

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }



    private void serializeConnection(Conn connection)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Conn));
        TextWriter textWriter = new StreamWriter(@"serialized.xml");
        serializer.Serialize(textWriter, connection);
        textWriter.Close();
    }

    static List<Conn> deserializeConnection()
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<Conn>));
        TextReader textReader = new StreamReader(@"serialized.xml");
        List<Conn> connectionList;
        connectionList = (List<Conn>)deserializer.Deserialize(textReader);
        textReader.Close();

        return connectionList;
    }

    private void btnSerialize_Click(object sender, EventArgs e)
    {
        Conn conn = getConnection();
        serializeConnection(conn);

    }

    private Conn getConnection()
    {
        Conn connection = new Conn();
        connection.connectionName = txtName.Text;
        connection.address = txtAddress.Text;
        connection.height = 2542;
        connection.width = 4254;
        connection.password = txtPassword.Text;
        connection.smartSizing = false;
        connection.username = txtUsername.Text;
        connection.port = 474;
        return connection;
    }

    private void btnDeserialize_Click(object sender, EventArgs e)
    {
        int count = deserializeConnection().Count;
        lblStatus.Text = "Count: " + count;
    }
}

class Conn
{
    public Conn()
    {
    }
    public string connectionName { get; set; }
    public int height { get; set; }
    public int width { get; set; }
    public string address { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public int port { get; set; }
    public bool smartSizing { get; set; }
}

}

类是公共 - 我不明白,这可能是造成这个错误。 任何帮助,将不胜感激。

Answer 1:

类是公共

不,这不对。 这里的声明:

class Conn
{
    ...
}

您还没有指定任何访问修饰符,所以它的默认为internal (假设它的非嵌套)。 只是因为它有一个公共的构造并不把它公开。 你需要把它公开明确:

public class Conn
{
    ...
}


文章来源: Public Class - “is inaccessible due to its protection level. Only public types can be processed.”