“this"的使用关键词

编程入门 行业动态 更新时间:2024-10-10 00:24:55
本文介绍了“this"的使用关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 16:41:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关键词   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!