基本的GUI事件处理问题C# [英] Basic GUI Event Handling Questions C#

查看:207
本文介绍了基本的GUI事件处理问题C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好,

我对GUI事件处理有一些非常基本的问题。首先用C#我们如何将事件链接到对象 - 我猜猜事件处理程序?每个处理程序是否可以使用单独的代码? - 事件处理程序如何找到必须操作的对象?

I have some very basic questions on GUI Event Handling. Firstly with C# how can we link events to objects - I am guessing event handlers? If so can each handler use separate code? - How can the event handler locate the objects it must manipulate?

我有一个大概的想法,它在JAVA中的工作原理。指向我的参考将是正常的 - 我已经拖网谷歌的答案无济于事。

I have a rough idea of how it works in JAVA. Pointing me towards a reference would be fine - I have already trawled Google for answers to no avail.

许多谢谢,
J

Many Thanks, J

推荐答案


首先用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.

这篇关于基本的GUI事件处理问题C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆