[C#]thisでクラスのインスタンス変数を使う方法

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class クラス名 {
データ型 変数名 = xxx;
public 戻り値の型 関数名 {
Console.WriteLine(this.変数名);
}
}
public class クラス名 { データ型 変数名 = xxx; public 戻り値の型 関数名 { Console.WriteLine(this.変数名); } }
public class クラス名 {
  データ型 変数名 = xxx;
  
  public 戻り値の型 関数名 {
      Console.WriteLine(this.変数名);
  }
}

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
//クラスUserの定義
public class User
{
//インスタンス変数の宣言
string target = "study skill ";
int age = 33;
public void funA()
{
//ローカル変数の宣言
string target = "become smart";
int age = 22;
// thisでクラスのインスタンス変数を表示
Console.WriteLine("thisで現在のインスタンスの変数: "+this.target);
Console.WriteLine("thisで現在のインスタンスの変数: " + this.age);
Console.WriteLine("***************");
// ローカル変数を表示
Console.WriteLine("ローカル変数: "+target);
Console.WriteLine("ローカル変数: " + age);
Console.ReadKey();
}
}
class Arkgame
{
public static void Main()
{
// Userクラスのインスタンスを生成
User cft = new User();
// インスタンスのメソッドを実行
cft.funA();
}
}
using System; //クラスUserの定義 public class User { //インスタンス変数の宣言 string target = "study skill "; int age = 33; public void funA() { //ローカル変数の宣言 string target = "become smart"; int age = 22; // thisでクラスのインスタンス変数を表示 Console.WriteLine("thisで現在のインスタンスの変数: "+this.target); Console.WriteLine("thisで現在のインスタンスの変数: " + this.age); Console.WriteLine("***************"); // ローカル変数を表示 Console.WriteLine("ローカル変数: "+target); Console.WriteLine("ローカル変数: " + age); Console.ReadKey(); } } class Arkgame { public static void Main() { // Userクラスのインスタンスを生成 User cft = new User(); // インスタンスのメソッドを実行 cft.funA(); } }
using System;

//クラスUserの定義
public class User
{
    //インスタンス変数の宣言
    string target = "study skill ";
    int age = 33;

    public void funA()
    {
        //ローカル変数の宣言
        string target = "become smart";
        int age = 22; 

        // thisでクラスのインスタンス変数を表示
        Console.WriteLine("thisで現在のインスタンスの変数: "+this.target);
        Console.WriteLine("thisで現在のインスタンスの変数: " + this.age);
        
        Console.WriteLine("***************");

        // ローカル変数を表示
        Console.WriteLine("ローカル変数: "+target);
        Console.WriteLine("ローカル変数: " + age);

        Console.ReadKey();
    }
}

class Arkgame
{

    public static void Main()
    {
        // Userクラスのインスタンスを生成
        User cft = new User();

        // インスタンスのメソッドを実行
        cft.funA();
    }
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
thisで現在のインスタンスの変数: study skill
thisで現在のインスタンスの変数: 33
***************
ローカル変数: become smart
ローカル変数: 22
thisで現在のインスタンスの変数: study skill thisで現在のインスタンスの変数: 33 *************** ローカル変数: become smart ローカル変数: 22
thisで現在のインスタンスの変数: study skill
thisで現在のインスタンスの変数: 33
***************
ローカル変数: become smart
ローカル変数: 22

 

C#

Posted by arkgame