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);
本文详细介绍了C#中this关键字的多种用途,包括表示当前对象、在构造函数中传递自身实例、实现索引器功能及为基本类型扩展方法等。通过具体示例展示了this关键字如何提高代码的清晰度和可维护性。
1万+

被折叠的 条评论
为什么被折叠?



