且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基本的GUI事件处理问题C#

更新时间:2023-11-21 21:40:22


首先用C#我们如何将事件
链接到对象 - 我猜测事件
处理程序?每个处理程序可以使用
单独的代码吗?

Firstly with C# how can we link events to objects - I am guessing event handlers? If so can each handler use separate code?

是的,每个事件处理程序都可以有自己的代码:

Yes, each event handler can have its own code:

class A {
    public event EventHandler SomeEvent;
}

class B {
    public B(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("B's handler"); };
    }
}

class C {
    public C(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("C's handler"); };
    }
}




处理程序找到必须操作的
对象?

How can the event handler locate the objects it must manipulate?

我要简化这个很多,但事件处理程序本质上围绕观察者模式的包装。像任何其他Delegate类型的EventHandler会保存方法调用列表中的订阅者列表(请参阅 Delegate.GetInvocationList )。你可以这么想:

I'm going to oversimplify this a lot, but event handlers are essentially wrappers around the observer pattern. EventHandlers like any other Delegate type hold a list of subscribers in a method invocation list (see Delegate.GetInvocationList). You can think of it like this:

class EventHandler {
    LinkedList<Action<object, EventArgs>> subscribers =
        new LinkedList<Action<object, EventArgs>>();

    public void Add(Action<object, EventArgs> f) {
        subscribers.AddLast(f);
    }

    public void Remove(Action<object, EventArgs> f) {
        subscribers.Remove(f);
    }

    public void Invoke(object sender, EventArgs e) {
        foreach(Action<object, EventArgs> f in subscribers)
            f(sender, e);
    }
}

(上面的代码远离实际代理类型是不可变的,所以添加一个处理程序会返回一个新的Delegate,而处理程序被添加,而不是使处理程序变为现实,我相信他们的Add / Remove方法有很多线程的voodoo

(The code above is pretty far removed from the actual implementation details of the real event handler class. Delegate types are immutable, so adding a handler returns a new Delegate with the handler added rather than mutating the handler in place. I believe their Add/Remove methods have a lot of threading voodoo in them as well.)

由于委托实例持有其每个订阅者的引用,因此可以直接访问其操作的任何对象。

Since the delegate instance holds a reference to each of its subscribers, it has direct access to any object it manipulates.