Događaji
Izgradite inteligentne aplikacije
M03 17 21 - M03 21 10
Pridružite se seriji susreta kako biste sa kolegama programerima i stručnjacima izgradili skalabilna AI rješenja zasnovana na stvarnim slučajevima korištenja.
Registrirajte seOvaj preglednik više nije podržan.
Nadogradite na Microsoft Edge da iskoristite najnovije osobine, sigurnosna ažuriranja i tehničku podršku.
The this
keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
Bilješka
This article discusses the use of this
with class instances. For more information about its use in extension methods, see Extension Methods.
The following are common uses of this
:
To qualify members hidden by similar names, for example:
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;
}
}
To pass an object as a parameter to other methods, for example:
CalcTax(this);
To declare indexers, for example:
public int this[int param]
{
get { return array[param]; }
set { array[param] = value; }
}
Static member functions, because they exist at the class level and not as part of an object, do not have a this
pointer. It is an error to refer to this
in a static method.
In this example, this
is used to qualify the Employee
class members, name
and alias
, which are hidden by similar names. It is also used to pass an object to the method CalcTax
, which belongs to another class.
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();
}
}
/*
Output:
Name: Mingda Pan
Alias: mpan
Taxes: $240.00
*/
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
.NET povratne informacije
.NET je projekat otvorenog koda. Odaberite vezu za pružanje povratnih informacija:
Događaji
Izgradite inteligentne aplikacije
M03 17 21 - M03 21 10
Pridružite se seriji susreta kako biste sa kolegama programerima i stručnjacima izgradili skalabilna AI rješenja zasnovana na stvarnim slučajevima korištenja.
Registrirajte se