1.用在类的属性、实例方法或实例构造方法中,区分成员名和本地变量(或参数)。
1 public class ExercisesTest 2 { 3 private int iValue = 99;//声明一个int类型的字段iValue=0 4 private string sValue = "";//声明一个string类型的字段sValue 5 6 /// <summary> 7 /// 定义一个方法,传入两个参数 8 /// </summary> 9 /// <param name="iValue"></param> 10 /// <param name="sValue"></param> 11 public void ShowTest(int iValue,string sValue) 12 { 13 // "this"表示ExercisesTest类的当前实例 14 // 在这里通过this可以在语义上区分成员名和参数名 15 this.iValue += iValue; 16 this.sValue ="Hello"+ sValue; 17 Console.WriteLine($"this.iValue={this.iValue} this.sValue={this.sValue}"); 18 Console.WriteLine($"iValue={iValue} sValue={sValue}"); 19 20 } 21 } 22 test.ShowTest(100, "James Kung");

2.this表示的是当前对象,可以把它作为实参传递到其它方法。
1 public class Test2 2 { 3 // 声明一个计算的方法,参数类型为Test1 4 public static int ShowAddResult(Test1 test1,int iValue) 5 { 6 int result = iValue+test1.iValue; 7 Console.WriteLine($"{iValue}+{test1.iValue}={result}"); 8 return result; 9 10 }
11
1 public class Test1 2 { 3 public int iValue = 99;//声明一个int类型的字段iValue=0 4 5 public Test1(int iValue) 6 { 7 // "this"表示Test1类的当前实例 8 // 在这里通过this可以在语义上区分成员名和参数名 9 this.iValue += iValue; 10 int result= iValue + Test2.ShowAddResult(this,0); 11 } 12 13 }
1 Test1 test = new Test1(50); 2 int result = Test2.ShowAddResult(test,80);//把test1的运算结果传递给方法。

3.可以利用this关键字来串联构造函数。
1 public class Test3 2 { 3 public Test3() 4 { 5 Console.WriteLine("这里是Test3的无参构造函数"); 6 } 7 public Test3(string name):this() 8 { 9 Console.WriteLine("这里是Test3中带一个参数的构造函数"); 10 } 11 public Test3(string name, int age):this(name) 12 { 13 Console.WriteLine("这里是Test3中带两个参数的构造函数"); 14 } 15 }
Test3 test = new Test3(); Console.WriteLine("**********************"); Test3 test1 = new Test3("维达");//这里会先去调用无参构造 Console.WriteLine("**********************"); Test3 test2 = new Test3("哈喽",8);//同上,调用无参构造,再调用一个参数构造。。。

4、扩展方法。
- 它必须在一个非嵌套、非泛型的静态类中(所以扩展方法一定是静态方法)
- 它至少要有一个参数
-
第一个参数必须加上this关键字作为前缀
- 第一个参数类型也称为扩展类型(extended type),表示该方法对这个类型进行扩展
- 第一个参数不能用其他任何修饰符(比如out或ref)
- 第一个参数的类型不能是指针类型
-
1 public static class ExtentionDemo//扩展方法必须是非泛型的静态类中 2 { 3 4 /// <summary> 5 /// 1、静态类 静态方法,必须有一个参数,第一个参数前面this关键字。 6 /// </summary> 7 /// <param name="num"></param> 8 /// <returns></returns> 9 public static bool IsBool(this int num) 10 { 11 return num % 2 == 0; 12 } 13 public static bool IsBool(this int num,string name) 14 { 15 //dosomething........... 16 return num % 2 == 0; 17 } 18 }
浙公网安备 33010602011771号