开发者

The this reference? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

When do you use the “this” keyword?

Can anyone explain me the "this" reference? when we use this ? w开发者_如何学JAVAith a simple example.


When you use this inside a class, you're refering to the current instance: to the instance of that class.

public class Person {

    private string firstName;
    private string lastName;

    public Person(string firstName, string lastName) {

        //How could you set the first name passed in the constructor to the local variable if both have the same?
        this.firstName = firstName;
        this.lastName = lastName;
    }

    //...
}

In the above example, this.firstName is refering to the field firstName of the current instance of the class Person, and firstName (the right part of the assignment) refers to the variable defined in the scope of the constructor.

So when you do:

Person me = new Person("Oscar", "Mederos")

this refers to the instance Person instance me.

Edit:
As this refers to the class instance, cannot be used inside static classes.

this is used (too) to define indexers in your classes, like in arrays: a[0], a["John"],...


this is a scope identifier. It is used within an object's instance methods to identify behaviors and states that belong to an instance of the class.


Nowadays-fashionable Fluent APIs use this extensively. Basically it's used to get hold of a reference to the current instance.


here's a simple example

public class AnObject
{
  public Guid Id { get; private set;}
  public DateTime Created {get; private set; }

  public AnObject()
  {
    Created = DateTime.Now;
    Id = Guid.NewGuid();
  }

  public void PrintToConsole()
  {
    Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
  }
}

public Main(string[] args) 
{
  var obj = new AnObject();
  obj.PrintToConsole();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜