C# 二进制格式化程序类型UserControl未标记为可序列化
我正在尝试使用C# 二进制格式化程序类型UserControl未标记为可序列化,c#,serialization,C#,Serialization,我正在尝试使用BinaryFormatter序列化我的对象: private UserSettings _userSettings; var serializer = new BinaryFormatter(); using (var file = new FileStream(@"D:\test.bin", FileMode.Create)) { serializer.Serialize(file, _userSettings); } 但我有一个奇怪的例外: 程序集“xxx”中的类型
BinaryFormatter
序列化我的对象:
private UserSettings _userSettings;
var serializer = new BinaryFormatter();
using (var file = new FileStream(@"D:\test.bin", FileMode.Create))
{
serializer.Serialize(file, _userSettings);
}
但我有一个奇怪的例外:
程序集“xxx”中的类型“MyCustomUserControl”未标记为
可序列化
类
UserSettings
没有对MyCustomUserControl
的任何引用,但它被MyCustomUserControl
引用。要使用BinaryFormatter
序列化程序,您的类需要标记为可序列化的。以下是一个例子:
[Serializable]
public class MyCustomUserControl: Control
{
//
}
控件的引用可以隐藏在事件中。如果UserSettings
类实现了控件订阅的事件,请将[字段:非序列化]
属性添加到事件:
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
您是否已将[Serializable]
用于CustomUserControl?如果您需要对序列化过程进行细粒度控制,您还可以手动实现ISerializable来解决此问题。@Kevin谢谢您的提醒。它不是[Serializable()]
而不是[Serializable]
@peterpep不必写括号。您甚至可以像SerializableAttribute()
那样编写,但是[Serializable]
就足够了。[Serializable]可以工作,但我的问题是对控件的引用隐藏在事件中。