Да, это ссылка на объект, для которого вызывается FooHandler()
.Делегаты могут ссылаться как на статические, так и на нестатические методы.Говоря о нестатических, 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