例如,我有一个这样的类:
[Serializable]
public class CustomClass : INotifyPropertyChanged
{
private bool _checkbox;
public int Value { get; set; }
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
NotifyPropertyChanged("Checkbox");
}
}
public int SecondValue { get; set; }
public string Text { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
编译它会给出一个 错误,即
公共事件 PropertyChangedEventHandler PropertyChanged;无法序列化。
为此,有必要将事件部分指定为NonSerialized,
[Serializable]
public class CustomClass : INotifyPropertyChanged
{
private bool _checkbox;
public int Value { get; set; }
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
NotifyPropertyChanged("Checkbox");
}
}
public int SecondValue { get; set; }
public string Text { get; set; }
[NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
如果我这样做,我会再次收到错误消息。
NonSerialized 不是字段类型,因此您需要将其正确指定为字段类型。
NonSerialized 不是字段类型,因此您需要将其正确指定为字段类型。
[Serializable]
public class CustomClass : INotifyPropertyChanged
{
private bool _checkbox;
public int Value { get; set; }
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
NotifyPropertyChanged("Checkbox");
}
}
public int SecondValue { get; set; }
public string Text { get; set; }
[field: NonSerialized] ///変更点ここ
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
自
现在您可以使用 INotifyPropertyChanged 序列化类。