如何摆脱NullReferenceException错误

时间:2013-08-31 19:24:08

标签: c#

我收到此错误NullReferenceException was unhandled by user code。此行发生错误

PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));

我尝试if( this != null)但仍然出错。我怎么摆脱它?

代码如下所示:

public int AboveAircraft
{
        get { return _above; }
        set
        {
            if (SetProperty(ref _above, value, "AboveAircraft") && _updateModel)
            {
                if (Model.AltitudeBand == null)
                {
                    Model.AltitudeBand = new AltitudeBand();
                }

                if (this != null && AboveAircraft != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));
                    if (_above < _below)
                    {
                        BelowAircraft = _above;
                    }
                }

                Model.AltitudeBand .Above = new AltitudeBandLimit() { Unit = AltitudeUnit.Foot, Value = _above };
            }
        }
}

1 个答案:

答案 0 :(得分:6)

您需要检查PropertyChanged是否为空:

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));
}

如果在其他地方至少注册了一个处理程序,它将不会为空。