What is the meaning of “this” in C#

前端 未结 8 1286
猫巷女王i
猫巷女王i 2020-12-07 01:44

Could anyone please explain the meaning \"this\" in C#?

Such as:

// complex.cs
using System;

public struct Complex 
{
   public int real;
   public          


        
8条回答
  •  甜味超标
    2020-12-07 02:05

    When the body of the method

    public Complex(int real, int imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
    

    is executing, it is executing on a specific instance of the struct Complex. You can refer to the instance that the code is executing on by using the keyword this. Therefore you can think of the body of the method

    public Complex(int real, int imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
    

    as reading

    public Complex(int real, int imaginary) {
        assign the parameter real to the field real for this instance
        assign the parameter imaginary to the field imaginary for this instance
    }
    

    There is always an implicit this so that the following are equivalent

    class Foo {
        int foo;
        public Foo() {
            foo = 17;
        }
    }
    
    class Foo {
        int foo;
        public Foo() {
            this.foo = 17;
        }
    }
    

    However, locals take precedence over members so that

    class Foo {
        int foo;
        public Foo(int foo) {
            foo = 17;
        }
    }
    

    assigns 17 so the variable foo that is a parameter to the method. If you want to assign to the instance member when you have a method where there is a local with the same name, you must use this to refer to it.

提交回复
热议问题