gpt4 book ai didi

c# - 这个字段怎么为空?

转载 作者:太空狗 更新时间:2023-10-29 17:43:06 26 4
gpt4 key购买 nike

我得到一个空异常,但该字段被初始化为一个空列表。那么它怎么可能为空呢?

错误发生在该方法的第二行(在 _hydredProperties 上):

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);
}
}

这是完整的类(class)(删除了评论和不相关的部分):

[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
}

关于c# - 这个字段怎么为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com