当我为 csharp 编写事件处理程序时,它看起来像这样:
public void FooHandler(object sender, EventArgs e)
{
//do stuff..
this.doSomething(); //Does the "this" keyword mean something in this context?
}
“this”关键字在这种情况下是否意味着什么?
编辑:
假设我也有这段代码:
public class GizmoManager {
public void Manage() {
g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
}
}
this
(在 FooHandler
中)指的是什么?
最佳答案
是的,它是对调用 FooHandler()
的对象的引用。委托(delegate)能够引用静态和非静态方法。在谈论非静态的时,this
是对对象实例的引用。
class A
{
public delegate void MyDelegate(object sender, int x);
public event MyDelegate TheEvent;
public void func()
{
if(TheEvent != null) TheEvent(this, 123);
}
}
class B
{
public B()
{
A a = new A();
a.TheEvent += handler;
a.func();
}
public void handler(object sender, int x)
{
// "sender" is a reference to object of type A that we've created in ctor
// "x" is 123
// "this" is a reference to B (b below)
}
}
B b = new B(); // here it starts
更多细节。您的代码:
g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
可以这样重写
g = new Gizmo();
g.Foo += new EventHandler(this.FooHandler); // look here
在这种情况下,this
与您的处理程序中的 this
相同;-)
更重要的是,如果您在理解 this
时遇到一些问题:
class X
{
int a;
public X(int b)
{
this.a = b; // this stands for "this object"
// a = b is absolutely the same
}
public X getItsThis()
{
return this;
}
}
X x = new X();
X x2 = x.getItsThis();
// x and x2 refer to THE SAME object
// there's still only one object of class X, but 2 references: x and x2
关于c# - 在谈论事件处理程序时,关键字 this 在 C# 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7026539/