提问者:小点点

C#事件处理程序对其他引用不可用


我有一节范例课。它有一个附加了事件处理程序的ObservableCollection。

class SomeItem
{
    public ObservableCollection<Thing> Things = new ObservableCollection<Thing>();
    
    private SomeEventHandler(object Sender, NotifyCollectionChangedEventArgs E)
    {
        //do something
    }
    
    public SomeItem()
    {
        this.Things.CollectionChanged += SomeEventHandler;
    }
}

我正在执行以下代码:

SomeItem Instance = new SomeItem();

Instance.Things.Add(new Thing()); // SomeEventHandler executed;

SomeItem AnotherReference = Instance;

AnotherReference.Things.Add(new Thing()); // SomeEventHandler NOT executed

如果从AnotherReference访问集合,为什么不执行事件处理程序?


共1个答案

匿名用户

我无法再现问题。这段代码按预期工作。

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args) {

            SomeItem Instance = new SomeItem();
          
            Instance.Things.Add(new Thing()); // SomeEventHandler executed;
            
            SomeItem AnotherReference = Instance;
            
            AnotherReference.Things.Add(new Thing()); // SomeEventHandler ALSO executed
        }
    }

    class Thing { 
    }

    class SomeItem
    {
        public ObservableCollection<Thing> Things = new ObservableCollection<Thing>();

        private void SomeEventHandler(object sender, NotifyCollectionChangedEventArgs e) {
            Console.WriteLine("Hello from SomeEventHandler");
        }

        public SomeItem() {
            this.Things.CollectionChanged += SomeEventHandler;
        }
    }
}

结果:

Hello from SomeEventHandler
Hello from SomeEventHandler
Press any key to continue.