this (C# リファレンス)this (C# Reference)
this
キーワードはクラスの現在のインスタンスを参照します。拡張メソッドの最初のパラメーターの修飾子としても使用されます。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.
注意
ここでは、クラス インスタンスでの this
の使用について説明します。This article discusses the use of this
with class instances. 拡張メソッドでの使用の詳細については、「拡張メソッド」を参照してください。For more information about its use in extension methods, see Extension Methods.
this
の一般的な使い方を次に示します。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; } }
静的メンバー関数は、クラス レベルで存在し、オブジェクトの一部ではないため、this
ポインターがありません。Static member functions, because they exist at the class level and not as part of an object, do not have a this
pointer. 静的メソッドで this
を参照するとエラーになります。It is an error to refer to this
in a static method.
例Example
この例では、似た名前によって非表示にされている Employee
クラスのメンバー name
と alias
を修飾するために this
が使用されています。In this example, this
is used to qualify the Employee
class members, name
and alias
, which are hidden by similar names. また、別のクラスに属するメソッド CalcTax
にオブジェクトを渡すためにも使用されています。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
*/
C# 言語仕様C# language specification
詳細については、「C# 言語の仕様」を参照してください。For more information, see the C# Language Specification. 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。The language specification is the definitive source for C# syntax and usage.
関連項目See also
フィードバック
フィードバックを読み込んでいます...