C# 即使在我注册了属性更改事件之后,它仍然为null

C# 即使在我注册了属性更改事件之后,它仍然为null,c#,wpf,inotifypropertychanged,C#,Wpf,Inotifypropertychanged,我使用INotifyPropertyChanged在类中的特定对象的变量发生任何更改时通知类 以下是课程: public class MyClass { public SecClass MyObj { get; set; } //A few more variables } 二等舱: public class SecClass:INotifyPropertyChanged { private bool _noti= false; publ

我使用
INotifyPropertyChanged
在类中的特定对象的变量发生任何更改时通知类

以下是课程:

 public class MyClass
 {
        public SecClass MyObj { get; set; }

     //A few more variables
 }
二等舱:

 public class SecClass:INotifyPropertyChanged
 {
    private bool _noti= false;

    public bool Noti
    {
        get { return _noti; }
        set
        {
            _noti= value;
            NotifyPropertyChanged("Noti");
        }
    }

     //A few more variables
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string name)
    {
      if (PropertyChanged != null)
      {
       PropertyChanged(this, new PropertyChangedEventArgs(name));
       }
    }
 }
下面是我的事件注册函数:

    public void Register()
    {
      MyObj.PropertyChanged += MyObj_PropertyChanged;         
    }

函数起作用,注册完成,但当涉及到更改时,它会将
属性更改显示为null(我猜在某个地方注册已删除,在发生更改之前,我如何检查它?

我将此与以下内容连接在一起:

static class Program
{
    static void Main()
    {
        var c = new MyClass();
        c.MyObj = new SecClass();
        c.Register();
        c.MyObj.Noti = !c.MyObj.Noti;
    }
}
添加(用于说明):

MyClass
,以及:

public event PropertyChangedEventHandler PropertyChanged;
SecClass
(让它们编译),它可以在运行时精细打印
“Noti”
。理论上存在线程争用,但在任何正常使用情况下都不太可能,但建议使用:

var handler = PropertyChanged;
if (handler != null)
{
    handler(this, new PropertyChangedEventArgs(name));
}
另外,请注意:如果将
[CallerMemberName]
添加到该属性中,则不需要显式指定属性:

private void NotifyPropertyChanged([CallerMemberName] string name = null) {...}
与:


但从根本上说:“无法复制”——它工作得很好。我想知道它是否与您的
PropertyChanged
实现有关,因为您实际上并没有显示这一点。特别是,我想知道您是否真的有两个事件:一个是显式实现的。这意味着您的演员对它的处理方式有所不同。

请在注册位置显示一些代码eventhandler@bash.d你的意思是像
Register
方法一样?你创建对象并初始化它的代码我猜你在注册后正在更改属性,或者您正在某处更改MyObj属性的实例。您还有一个冗余强制转换。@devdigital由于未显示
PropertyChanged
声明,因此我们无法确定强制转换是否冗余,因此我的答案中的最后一行(怀疑它是否实际实现了双重,这可能会导致问题)
private void NotifyPropertyChanged([CallerMemberName] string name = null) {...}
NotifyPropertyChanged(); // the compiler adds the "Noti" itself