this 指的是当前对象.但无法理解以下行为 [英] this refers to current object. But can't understand the below behaviour

查看:35
本文介绍了this 指的是当前对象.但无法理解以下行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Person
{
    string name;

    public Person(string name)
    {
        this.name = name;
    }

    public void method()
    {
        Person gupta = new Person("James"); // Current Object
        Console.WriteLine(this.name);
        Person gupta1 = new Person("Peter");  // Current Object
        Console.WriteLine(this.name);
        Person gupta2 = new Person("Frank");  // Current Object
        Console.WriteLine(this.name);
    }

    static void Main(string[] args)
    {
        Person p = new Person("Jim");
        p.method();
        Console.ReadLine();
    }
}

这段代码产生了结果

Jim
Jim
Jim

但是如果认为这应该是

James
Peter
Frank

有人能解释一下吗?

推荐答案

当前对象"是一种相当非正式的表达方式.只要您不混淆它所指的内容就可以.

"Current object" is a rather informal way of speaking. It is ok as long as you don't get confused about what it refers to.

不要将其视为一种按时间顺序"的度量 - 当前对象"不是您上次实例化的对象.相反,它是在其上调用方法当前执行的类的实例.

Do not think of it as a kind of "chronological" measure - the "current object" is not the very object you last instantiated anywere. Instead, it is the instance of the class on which you called the current execution of the method.

在撰写this.(...)"时,您不知道 将是哪个实例.现在,当代码被调用时,您将这样做.

At the time of writing "this.(...)", you don't know which instance it will be. You will now when the code is called.

Person somePerson = new Person("Lucy");
somePerson.method();

在这个对 method 的调用中,this"将是 Lucy - 因为方法 method 是在 Person 的特定实例上调用的.您在 method 中创建的小 Person 完全不会影响这一点.

Inside this call to method, "this" will be Lucy - because the method method is being called on that particular instance of Person. The little Persons you create inside method will not affect this at all.

进一步说明:

Person somePerson = new Person("Lucy");
somePerson.method(); // inside method, "this" is Lucy.

Person somePerson = new Person("Anne");
somePerson.method(); // inside method, "this" is Anne.

Person somePerson = new Person("Sarah");
somePerson.method(); // inside method, "this" is Sarah.

Person somePerson = new Person("Emily");
somePerson.method(); // inside method, "this" is Emily.

这篇关于this 指的是当前对象.但无法理解以下行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆