问题描述
限时送ChatGPT账号..我正在研究 this
的用法,我想我至少部分理解它,比如何时解决歧义和从当前"类调用方法,但是一个例子来自我正在阅读的书(Head First C#)让我很难受:
I'm studying the uses of this
and I think I understand it, at least partially, like when to solve ambiguity and to call methods from the "current" class, but one example from the book I'm reading(Head First C#) is giving me a hard time:
public void SpeakTo(Elephant whoToTalkTo, string message) {
whoToTalkTo.TellMe(message, this);
}
在这个方法中,可以肯定地说 this
具有始终引用调用方法 SpeakTo()
的任何对象的功能,无论是哪个类电话写在?
In this method, is it safe to say that the this
has the function of always refering to whatever object calls the method SpeakTo()
, regardless of which class the call is written in?
推荐答案
在这个方法中,是否可以肯定地说this"具有始终引用调用方法SpeakTo()"的任何对象的功能,而不管调用是在哪个类中编写的?
In this method, is it safe to say that the "this" has the function of always refering to whatever object calls the method "SpeakTo()", regardless of which class the call is written in?
没有.this
不引用调用SpeakTo
的对象.它指的是调用 SpeakTo
的对象.
Nope. this
does not refer to the object that calls SpeakTo
. It refers to the object on which SpeakTo
is called.
我会用一些代码来澄清这一点
I will use some code to clarify this point
class Foo {
public static void Main(String[] args) {
var foo = new Foo();
foo.MyMethod();
}
public void MyMethod() {
var bar = new Bar();
bar.SpeakTo(anElephant, "Hello");
}
}
class Bar {
public void SpeakTo(Elephant whoToTalkTo, string message) {
whoToTalkTo.TellMe(message, this);
}
}
根据你的说法,this
指的是在 main 方法中创建的 foo
变量.这是不是的情况.this
实际上是指bar
.即方法名称之前的对象.
According to your statement, this
refers to the foo
variable that's created in the main method. This is not the case. this
actually refers to bar
. i.e. the object that's before the method name.
这篇关于“this"的使用关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论