我得到一个空的异常,但该字段已初始化为空列表.那么怎么可能是null?
该方法的第二行发生错误(在_hydratedProperties上):
protected virtual void NotifyPropertyChanged<T>(Expression<Func<T>> expression) { string propertyName = GetPropertyName(expression); if (!this._hydratedProperties.Contains(propertyName)) { this._hydratedProperties.Add(propertyName); } }
这就是这个领域如何被宣布:
public abstract class EntityBase<TSubclass> : INotifyPropertyChanged where TSubclass : class { private List<string> _hydratedProperties = new List<string>();
这是它的设置:
public Eta Eta { get { return this._eta; } set { this._eta = value; NotifyPropertyChanged(() => this.Eta); } }
这是完整的课程(删除了注释和非相关部分):
[DataContract] public abstract class EntityBase<TSubclass> : INotifyPropertyChanged where TSubclass : class { private List<string> _hydratedProperties = new List<string>(); public bool IsPropertyHydrated(string propertyName) { return this._hydratedProperties.Contains(propertyName); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void NotifyPropertyChanged<T>(Expression<Func<T>> expression) { string propertyName = GetPropertyName(expression); if (!this._hydratedProperties.Contains(propertyName)) { this._hydratedProperties.Add(propertyName); } PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this,new PropertyChangedEventArgs(propertyName)); } } public string GetPropertyName<T>(Expression<Func<T>> expression) { MemberExpression memberExpression = (MemberExpression)expression.Body; return memberExpression.Member.Name; } }
派生类:
[DataContract] public class Bin : EntityBase<Bin> { private Eta _eta; [DataMember] public Eta Eta { get { return this._eta; } set { this._eta = value; NotifyPropertyChanged(() => this.Eta); } } }
解决方法
以下是线索:
[DataContract]
对. DataContractSerializer
does not call any constructor.相反,它使用FormatterServices.GetUninitializedobject来创建将被反序列化的对象.这将绕过构造函数调用.
您的初始化程序:
private List<string> _hydratedProperties = new List<string>();
作为解决方法,您可以使用a deserialization callback with OnDeserializingAttribute
:
[DataContract] public abstract class EntityBase<TSubclass> : INotifyPropertyChanged where TSubclass : class { private List<string> _hydratedProperties; protected EntityBase() { Init(); } private void Init() { _hydratedProperties = new List<string>() } [OnDeserializing] private void OnDeserializing(StreamingContext context) { Init(); } // ... rest of code here }
原文地址:https://www.jb51.cc/csharp/91439.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。