1.和c++中一样,指当前的对象。
2.用于传递构造函数。eg
class TestA
{
public TestA()
{
Console.WriteLine("Default Constructor");
}
public TestA(int a)
: this()
{
Console.WriteLine("One parameter Constructor {0}",a);
}
public TestA(int a, int b)
: this(a)
{
Console.WriteLine("2 parameter constructor");
}
}
3.用于实现索引:
public class IndexTest
{
int[] a = new int[10];
public int this[int index]
{
get
{
return a[index];
}
set
{
a[index] = value;
}
}
}
这样就可以直接使用IndexTest对象的[]操作。
4.为原始类型扩展方法
扩张方法三要素:
- 静态类。
- 静态函数
- this关键字
比如扩展string
//1.静态类 public static class ExtentString { //静态函数+this.length是Fun函数的第一个参数。 public static int Fun(this string s, int length) { return s.Length + length; } }
使用的时候:
string _tempstring = "sfsfa"; _tempstring.Fun(10);