標籤:
this的五種用法:
1.使用被掩蓋的成員變數:
class AA
{
int a;
public void set1(int a)
{
this.a = a;//right
}
public void set2(int a)
{
a = a;//會有警告:“對同一變數進行賦值;是否希望對其他變數賦值?”;
}
}
2.把這個對象傳給其他函數
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ class BB { static public void set(AA t,int a) { t.set1(a); } } class AA { int a; public void set1(int a) { this.a = a; } public void set2(int a) { BB.set(this, a); } public int get() { return a; } } class Program { static void Main(string[] args) { AA t = new AA(); t.set2(123); Console.WriteLine(t.get()); } }}
3.With Indexers(索引器)//這個暫時不懂
4.調用其他建構函式
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{ class AA { int a, b; public AA(int a) { this.a = a; b = -1; print(); } public AA(int a,int b):this(a) { this.b = b; print(); } void print() { Console.WriteLine("{0} {1}", a, b); } } class Program { static void Main(string[] args) { AA t = new AA(1); t = new AA(1, 1); } }}
輸出:
1 -1
1 -1
1 1
5.是代碼更明確
如把
public AA(int a) { this.a = a; b = -1; print(); }
改為
public AA(int a) { this.a = a; this.b = -1; print(); }
C#this的五種用法