发布网友
发布时间:2022-04-25 16:46
共3个回答
热心网友
时间:2023-10-19 18:24
this 关键字引用类的当前实例。
以下是 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; }
}
由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有 this 指针。在静态方法中引用 this 是错误的。
示例
在本例中,this 用于限定 Employee 类成员 name 和 alias,它们都被相似的名称隐藏。this 还用于将对象传递到属于其他类的方法 CalcTax。
// keywords_this.cs
// this example
using System;
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("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}
输出
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
热心网友
时间:2023-10-19 18:24
其实和C++中的差不多,只不过C++里this是指针,用的时候要用->符号调用其成员,而C#中直接用取成员运算符.。
都代表this所在类的对象
热心网友
时间:2023-10-19 18:25
回答的不错