c# - c#序列化创建一个空文件
问题描述
我正在尝试用 c# 开发一个库应用程序,但我陷入了 ObservableCollection 类的序列化中。
功能测试是:
[TestMethod]
public void saveFile_createTheFile()
{
var btn_saveFile = createA<WpfButton>("btn_saveToFile");
if (fileManager.saveFileExists())
return;
btn_saveFile.Click();
fileManager.saveFileExists().ShouldBeTrue();
}
我认为它是自动记录的,易于理解。我面临 2 个问题: - 测试后,创建了一个保存文件,但测试失败消息告诉我 saveFileExists() 方法返回 false。- 保存文件在正确的目录中创建,但它是一个空文件,我不知道为什么。
这是我专门用于文件管理的工具类:
public class FileManager
{
private string SAVEFILE = "datas.saved";
public string appDir = null;
public string pathToSaveFile = null;
public FileManager()
{
appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
pathToSaveFile = Path.Combine(appDir, SAVEFILE);
}
public Boolean saveFileExists()
{
return File.Exists(Directory.GetCurrentDirectory() + "\\" + SAVEFILE);
}
public void saveToFile(ObservableCollection<Book> books)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(SAVEFILE, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, books.ToArray());
stream.Close();
}
}
有人能告诉我为什么我得到这两个错误吗?
谢谢你
ps:在启动时,集合包含 2 本书。Book 类是可序列化的。
编辑
我找到了原因:通过调试,我得到了这个错误:在“formatter.Serialize(...)”方法中,出现错误“PropertyChangeEventManager is not serializable”。确实,这是 Book 类:
[Serializable]
public class Book : INotifyPropertyChanged
{
public string _title;
public string title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged("title");
}
}
public string _author;
public string author
{
get { return _author; }
set
{
_author = value;
OnPropertyChanged("author");
}
}
public string _editor;
public string editor
{
get { return _editor; }
set
{
_editor = value;
OnPropertyChanged("editor");
}
}
public string _isbn;
public string ISBN
{
get { return _isbn; }
set
{
_isbn = value;
OnPropertyChanged("ISBN");
}
}
public DateTime _bookAdded;
public DateTime bookAdded
{
get { return _bookAdded; }
set
{
_bookAdded = value;
OnPropertyChanged("bookAdded");
}
}
public Book(string isbn,string title,string author,string editor, DateTime bookAdded)
{
this.title = title;
this.ISBN = isbn;
this.author = author;
this.editor = editor;
this.bookAdded = bookAdded;
}
public Book()
{
bookAdded=DateTime.Today;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这是一个子类,基类肯定添加了一些不可序列化的字段。我怎样才能避免这种情况?我是 wpf 的新手,但我认为 Book 中的通知是强制性的,以便告诉窗口的绑定组件已完成更改。
解决方案
推荐阅读
- django - Docker 容器的 Django 迁移
- angular - 错误类型错误:无法读取未定义 core.js:5967 的属性“toLocaleLowerCase”
- java - curl字符串中的变量(Java)
- python - Opencv相机校准:我需要使用标志吗?
- python - 熊猫数据框无法将毫秒保存到 csv
- html - 基于shopify的在线商店的集合过滤器错误
- clickhouse - 在 Clickhouse 中进行数据重新平衡的最佳方法
- node.js - DiscordJS Bot - 从站点获取 json
- sql - 考虑到子查询内部与外部子查询的过滤/分页的 Postgres SQL 性能
- angular - 如何将订阅逻辑从 ngOnInit 移动到 ngOnChange