Public Class - “is inaccessible due to its protection level. Only public types can be processed.”

心不动则不痛 提交于 2019-12-05 15:27:35

问题


I am doing a test project to learn about XML serialization of an object, and I am getting an odd runtime error:

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; }
}

}

The Class is public - I don't understand what could be causing this error. Any help would be appreciated.


回答1:


The Class is public

No it's not. Here's the declaration:

class Conn
{
    ...
}

You haven't specified any access modifiers, so it's defaulting to internal (assuming it's non-nested). Just because it's got a public constructor doesn't make it public. You need to make it public explicitly:

public class Conn
{
    ...
}


来源:https://stackoverflow.com/questions/11277605/public-class-is-inaccessible-due-to-its-protection-level-only-public-types-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!