C# this
C# this
在 C# 编程中,this 是指代当前类实例的关键字。这个关键字在 C# 中主要有 3 种用法。
可用于引用当前类实例变量。如果字段名称(实例变量)和参数名称相同,则使用它,这就是为什么两者很容易区分的原因。
它可以用于将当前对象作为参数传递给另一个方法。
它可用于声明索引器。
C#这个例子
我们来看看C#中this关键字引用当前类的字段的例子。
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int id, String name,float salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sonoo", 890000f);
Employee e2 = new Employee(102, "Mahesh", 490000f);
e1.display();
e2.display();
}
}
输出:
101 Sonoo 890000
102 Mahesh 490000
我们将在下一章中了解该关键字的其他用法。