NullReferenceException,带有属性列表的获取器(C#)

时间:2019-05-27 14:46:49

标签: c# properties

我具有以下属性:

private List<Game> gamesList;
public List<Game> GamesList
{
    get
    {
        return this.gamesList;
    }

    set
    {
        this.SetValue(ref this.gamesList, value); // NotifyPropertyChanged
    }
}

SetValue:

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void SetValue<T>(ref T backingfield, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingfield, value))
        {
            return;
        }
        else
        {
            backingfield = value;

            this.OnPropertyChanged(propertyName);
        }
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

}

我想这样做:

StreamReader sr = new StreamReader(response);
var dbResponse = sr.ReadToEnd();
sr.Close();
this.GamesList = JsonConvert.DeserializeObject<List<Game>>(dbResponse);

这会在GamesList的Getter中引发异常,我不知道是什么引起的。我从dbReponse获取的数据是正确的。

-

1 个答案:

答案 0 :(得分:0)

我认为您的程序中断的原因是您假设事件处理程序将保留引用。

尝试更改此内容:

this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));

对此:

this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

请注意空条件 ?.运算符。