当谈论事件处理程序时,关键字 this 在 C# 中意味着什么?
当我为 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
内)指的是什么?
When I write an event handler for csharp, it looks like this:
public void FooHandler(object sender, EventArgs e)
{
//do stuff..
this.doSomething(); //Does the "this" keyword mean something in this context?
}
Does the "this" keyword mean something in this context?
EDIT:
Let's say I also have this code:
public class GizmoManager {
public void Manage() {
g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
}
}
What would the this
(within FooHandler
) refer to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它是对调用
FooHandler()
的对象的引用。委托能够引用静态和非静态方法。当谈论非静态时,this
是对对象实例的引用。更多细节。您的代码:
可以像这样重写
在这种情况下
this
与您在处理程序中的this
相同 ;-)甚至更多,如果您遇到一些问题理解
这个
:Yes, it's a reference to object for which
FooHandler()
is called. Delegates are capable of referencing both static and non-static methods. When talking about non-static ones,this
is a reference to object instance.Some more details. Your code:
could be re-written like this
In this case
this
is the samethis
that you have in your handler ;-)And even more, if you have some problems with understanding
this
:更完整...
“this”将引用 Bar 的一个实例
more complete...
"this" will refer to an instance of Bar
this
将引用您当前所在的类,而不是方法。来自 MSDN,
在您的示例中,
this.doSomething()
引用该方法之外的某个任意类中的方法。这个
是多余的。在这种情况下使用
this
很有用:它有助于描述含义。否则,如果没有
this
,您真正指的是什么name
或alias
?最后,
sender
将引用引发事件的object
。this
is going to refer to the current class you are in, not the method.From MSDN,
In your example,
this.doSomething()
refers to a method in some arbitrary class outside of that method.this
is redundant.It is useful to use
this
in cases like this:It helps delineate between the meaning. Otherwise, without
this
whatname
oralias
are you really referring to?Finally,
sender
is going to refer to theobject
which raised the event.