在實現C#匯出List資料到xml檔案[附源碼]時遇到錯誤:因其保護層級而不可訪問。只能處理公用類型。
產生錯誤的程式碼:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<UserModel>));
錯誤原因:以下代碼中類定義為:
class UserModel
沒有添加public存取修飾詞
/// <summary> /// 使用者實體類 /// /// 注意:類的存取修飾詞必須是:public,否則會出現錯誤: /// 因其保護層級而不可訪問。只能處理公用類型。 /// </summary> [Serializable] public class UserModel { private long id = 1; private string name = "name"; private int gender = 0; private int age = 20; private string userName = "userName"; private string password = "password"; public long Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public int Gender { get { return gender; } set { gender = value; } } public int Age { get { return age; } set { age = value; } } public string UserName { get { return userName; } set { userName = value; } } public string Password { get { return password; } set { password = value; } } }