Csharp/CSharp Tutorial/Class/this

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call Constructor in the same class using "this"

<source lang="csharp">using System; class MyObject {

   public MyObject(int x)
   {
       this.x = x;
   }
   public MyObject(int x, int y): this(x)
   {
       this.y = y;
   }
   public int X
   {
       get
       {
           return(x);
       }
   }
   public int Y
   {
       get
       {
           return(y);
       }
   }
   int x;
   int y;

} class MainClass {

   public static void Main()
   {
       MyObject my = new MyObject(10, 20);
       Console.WriteLine("x = {0}, y = {1}", my.X, my.Y);
   }

}</source>

x = 10, y = 20

implicit this

<source lang="csharp">class MainClass

   {
       int state;
       public void Foo()
       {
           state++;
           this.state++;
       }
   }</source>

Use this to reference shadowed member variables

<source lang="csharp">using System; class MyObject {

   int x;
   int y;
   public MyObject(int x, int y)
   {
       this.x = x;
       this.y = y;
   }

}</source>