this 關(guān)鍵字將引用類(lèi)的當(dāng)前實(shí)例。靜態(tài)成員函數(shù)沒(méi)有 this 指針。this關(guān)鍵字可用于從構(gòu)造函數(shù)、實(shí)例方法和實(shí)例訪問(wèn)器中訪問(wèn)成員。
以下是 this 的常用用途:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
CalcTax(this);
public int this [int param]
{
get
{
return array[param];
}
set
{
array[param] = value;
}
}
在靜態(tài)方法、靜態(tài)屬性訪問(wèn)器或字段聲明的變量初始值設(shè)定項(xiàng)中引用 this 是錯(cuò)誤的。
在本例中,this 用于限定 Employee
類(lèi)成員 name
和 alias
,它們都被相似的名稱(chēng)隱藏。this還用于將對(duì)象傳遞到屬于其他類(lèi)的方法 CalcTax
。
// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public 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 class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
聯(lián)系客服