简体   繁体   English

如何找出谁订阅了事件字段?

[英]How do I find out who has subscribed to an event field?

I want to find out when the PropertyChanged event handler is set in my base class.我想知道何时在我的基础 class 中设置了 PropertyChanged 事件处理程序。

Both Debug.Print("Is Null") and Debug.Print("not null") get hit. Debug.Print("Is Null") 和 Debug.Print("not null") 都会被命中。 So it must get set somewhere.所以它必须设置在某个地方。 How do I find that out?我怎么知道呢?

A search for PropertyChanged does not reveal code that subscribes to the ebvent.搜索 PropertyChanged 不会显示订阅 ebvent 的代码。

public abstract class NonPersistentObjectBase : INotifyPropertyChanged, IObjectSpaceLink {
   
    public event PropertyChangedEventHandler PropertyChanged; // how do I break here
    protected void OnPropertyChanged(string propertyName) {
        if(PropertyChanged != null) {
            Debug.Print("not null"); // gets hit after I click save
        }
        else {
            Debug.Print("Is Null"); //gets hit
        }

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    protected void SetPropertyValue<T>(string name, ref T field, T value) {
        if(!Equals(field, value)) {
            field = value;
            OnPropertyChanged(name);
        }
    }

I added a private event as per Olivier's suggestion but am unsure how to call it.根据 Olivier 的建议,我添加了一个私人活动,但不确定如何调用它。 I tried assigning it in the constructor我尝试在构造函数中分配它

    private event PropertyChangedEventHandler PropertyChangedAdd {
        add =>  PropertyChanged += value;
        remove => PropertyChanged -= value;
    }

调用栈

We cannot add a breakpoint to such a single statement without an assignment.我们不能在没有赋值的情况下向这样的单个语句添加断点。

We can only add on a runtime instruction.我们只能添加运行时指令。

A void declaration as well as a method signature alone is not an real instruction to be executed: no assignment, no call, no loop, no test, no jump, no calculation... just a "static memory reservation" planned and done by the compiler at compile-time.单独的 void 声明和方法签名并不是要执行的真正指令:没有赋值、没有调用、没有循环、没有测试、没有跳转、没有计算……只是由计划和完成的“静态 memory 保留”编译时的编译器。

But we can implement add and remove accessors of a property-event on a real private field, thus we will be able to put breakpoints.但是我们可以在真正的私有字段上实现属性事件的添加和删除访问器,因此我们将能够放置断点。

Also, once that done, we can open the call stack window in Visual Studio or go out of the method toward the caller subscriber.此外,一旦完成,我们可以在 Visual Studio 中打开调用堆栈 window 或 go 向调用方订阅者的方法之外。

public event PropertyChangedEventHandler PropertyChanged
{
  add => _PropertyChanged += value;
  remove => _PropertyChanged -= value;
}
private event PropertyChangedEventHandler _PropertyChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM