基础的来说 this有三种作用
1隐藏类的成员
2 声明索引器
索引器和 属性的区别
-
索引器 可以 带参数索引index, 而属性没有参数
-
索引器可以重载的,根据参数的类型不同,各种重载。
-
索引器 的名字是this 。 而属性有自己的名字。
-
最重要的是,索引器本质上就是属性。 特殊的属性。因为 索引器最后 在编译的时候,会形成 item的属性
索引器类型表示该索引器使用哪一类型的索引来存取数组或集合元素,可以是整数,可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称。 例如:
class Z
{
//可容纳100个整数的整数集
private long[] arr = new long[100];
//声明索引器
public long this[int index]
{
get
{ //检查索引范围
if (index < 0 || index >= 100)
{
return 0;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}
类
{
数组
索引器 (index)
{
}
}
3 引用当前类的实例
c#用于引用当前类的实例 ,
来 用代码解释一下
首先 定义一个student 类
一个学生类肯定会有属性
比如 名字 年龄等
有了属性 做一个访问器 便于给属性赋值 在写一个方法打印 信息
代码如下
class Student
{
private string name;
private string alias;
private decimal salary = 3000;
public Student(string name, string alias)
{
this.name = name;
this.alias = alias;
}
public void printStudent()
{
Console.WriteLine("姓名:{0},性别:{1},工资:{2}", Name, Alias, salary);
Console.WriteLine("税款:{0}",Tax.CalcTax(this));
}
public decimal Salary
{
get { return salary; }
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Alias
{
get
{
return alias;
}
set
{
alias = value;
}
}
}
class Tax
{
public static decimal CalcTax(Student E)
{
return 0.08m * E.Salary;
}
}
class Program
{
static void Main(string[] args)
{
//Student E1 = new Student();
// E1.Name = "HUAN";
// E1.Alias = "MAN";
Student E1 = new Student("Mingda Pan", "mpan");
E1.printStudent();
Console.ReadLine();
}
}
}
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/this
这里 在另一个类中 用this引用 Sudent类的实例