c# - 在谈论事件处理程序时,关键字 this 在 C# 中意味着什么?

标签 c# events event-handling

当我为 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/

相关文章:

angularjs - 如何让 UI Bootstrap 选项卡在选项卡更改时发送事件

c# - 在 Moq 上使用与 UserManager 的接口(interface)

c# - 如何获得与 MariaDB 5.5.6 链接的 Visual Studio Community 2017?

javascript - jQuery:确定一个函数是否被调用为 jQuery 事件处理程序(回调)

javascript - 将参数传递给 redux 调度函数

C#:引发继承事件

c# - 在 C# 中使用 F# 数据类型

c# - 我在统一复制门时遇到问题

javascript - 为什么调用 javascript 函数的文本框 onchange 事件不起作用?

java - 调用其他有界上下文的策略