获取事件在 C# 中注册的对象的名称

Get the name of the object the event is registered on in C#

我已经像这样订阅了 ObservableCollection<string> m_myCollectionCollectionChanged 事件:

  private ObservableCollection<string> m_myCollection;
  public ObservableCollection<string> MyCollection
  {
     get => m_myCollection;
     set
     {
        m_myCollection= value;
        OnPropertyChanged();
     }
  }

  public ViewModel()
  {
     MyCollection = new ObservableCollection<string>();

     MyCollection.CollectionChanged += OnCollectionChanged;

     MyCollection.Add("Item 1");
  }

  private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  {
     // How to get the name of the collection here? That is: "MyCollection"
  }

如何获取方法中的集合名称?

ObservableCollection 个实例没有 "names"。并且任何数量的变量都可能保留对集合的引用。可能有 none,可能有十个。没有真正的 "automatic" 方法可以做到这一点。您真正能做的就是传递您自己周围的信息,例如,将您认为的集合的 "name" 传递给处理程序:

 MyCollection = new ObservableCollection<string>();
 MyCollection.CollectionChanged += (s, e) => HandleCollectionChanged("MyCollection", e);
 MyCollection.Add("Item 1");

或者,您可以创建自己的集合类型,可能会扩展 ObservableCollection,为它提供您在构造函数中设置的 Name 属性,然后可以稍后阅读.