一、this常见用法
this 关键字指代类的当前实例,还可用作扩展方法的第一个参数的修饰符【需要另行学习】。
以下是 this 的常见用法:
限定类中隐藏的成员
例如:
public class Employee
{
private string alias;
private string name;
public Employee(string name, string alias)
{
// Use this to qualify the members of the class
// instead of the constructor parameters.
this.name = name;
this.alias = alias;
}
}
将对象作为参数传递给方法
例如:
CalcTax(this);
声明索引器
例如:
public int this[int param]
{
get { return array[param]; }
set { array[param] = value; }
}
特别说明:
静态成员函数,因为它们存在于类级别且不属于对象,不具有 this 指针。 在静态方法中引用 this 会生成错误。【即在静态成员函数(包含static关键字)中不能引用/出现this关键字】
二、示例
在此示例中,this 用于限定类似名称隐藏的 Employee 类成员、name 和 alias。 它还用于将某个对象传递给属于其他类的方法 CalcTax。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Employee
{
private string name;
private string alias;
private decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
public decimal Salary
{
get { return salary; }
}
}
class Tax
{
public static decimal CalcTax(Employee E)
{
return 0.08m * E.Salary;
}
}
class MainClass
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("Mingda Pan", "mpan");
// Display results:
E1.printEmployee();
Console.ReadLine();
}
}
/*
Output:
Name: Mingda Pan
Alias: mpan
Taxes: $240.00
*/
}