c# – 该字段如何为空?

前端之家收集整理的这篇文章主要介绍了c# – 该字段如何为空?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我得到一个空的异常,但该字段已初始化为空列表.那么怎么可能是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
}

猜你在找的C#相关文章