鉴于:
public class MyClass : INotifyPropertyChanged
{
public List<string> _TestFire = new List<string>();
string _StringProp;
public string StringProp
{
get
{
return _StringProp;
}
set
{
if (_StringProp != value)
{
_StringProp = value;
RaisePropertyChanged("StringProp");
_TestFire.Add("fired " + DateTime.Now);
}
}
}
}
当您序列化然后反序列化此类时,它会触发
RaisePropertyChanged
事件,这是不可取的。是否可以防止在类反序列化时触发此事件?var MyclassInstance = new MyClass() { StringProp = "None" };
MyclassInstance._TestFire.Clear(); // Clear property change history
var serobj = JsonConvert.SerializeObject();
var newitem = JsonConvert.DeserializeObject<MyClass>(serobj);
// newitem._TestFire.Count == 1, the set method was executed
有没有办法获得
bool
如果类被反序列化,则值?那么我可以这样做:
set
{
if (_StringProp != value)
{
_StringProp = value;
if (!Deserializing)
{
RaisePropertyChanged("StringProp");
_TestFire.Add("fired " + DateTime.Now);
}
}
}
最佳答案
是的,您可以通过实现 OnDeserializing
来做您想做的事。和 OnDeserialized
serialization callback methods在你的类里面。在 OnDeserializing
方法,设置您的私有(private)_isDeserializing
变量为真,并在 OnDeserialized
将其重新设置为 false。我建议做 _isDeserializing
检查内部 RaisePropertyChanged
方法,因此您不会在每个属性中都有重复的代码。
所以你最终会得到这样的结果:
public class MyClass : INotifyPropertyChanged
{
public List<string> _TestFire = new List<string>();
string _StringProp;
public string StringProp
{
get
{
return _StringProp;
}
set
{
if (_StringProp != value)
{
_StringProp = value;
RaisePropertyChanged("StringProp");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
// don't raise the event if the property is being changed due to deserialization
if (_isDeserializing) return;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
_TestFire.Add(propertyName + " was fired " + DateTime.Now);
}
bool _isDeserializing = false;
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
_isDeserializing = true;
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
_isDeserializing = false;
}
}
工作演示:https://dotnetfiddle.net/QkOcF4
解决此问题的另一种方法是使用
[JsonIgnore]
标记您的公共(public)属性。然后用 [JsonProperty]
标记相应的支持字段,指定要在 JSON 中使用的属性名称。这将允许 Json.Net 直接设置支持字段,而不执行任何 mutator 逻辑。public class MyClass : INotifyPropertyChanged
{
public List<string> _TestFire = new List<string>();
[JsonProperty("StringProp")]
string _StringProp;
[JsonIgnore]
public string StringProp
{
get
{
return _StringProp;
}
set
{
if (_StringProp != value)
{
_StringProp = value;
RaisePropertyChanged("StringProp");
_TestFire.Add("StringProp was fired " + DateTime.Now);
}
}
}
...
}
工作演示:https://dotnetfiddle.net/jc7wDu
关于c# - INotifyPropertyChanged 和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641831/