LoginSignup
0
0

C# 勉強記録 1

Last updated at Posted at 2024-04-13

クラスのインスタンス化

クラスのインスタンス化とはクラスを使えるようにする事。
作成したクラスはそのままでは使用する事ができない。
必ずインスタンス化しないとクラスは使えない

インスタンス化の方法

program.cs
Sum sum = new Sum;
sum.text1 = "こんにちは";
sum.text1 = "皆さ~ん";

string text3 = sum.ReturnText();
console.WriteLine(text3);

コードの一行目のSum sum = new Sum;でインスタンスを生成。
変数にnew +クラス名とする事でインスタンス化する事ができる

この時の変数の型をvarとすると楽になる?みたい
なんで楽になるかはわかってない(勉強が必要)

classSum.cs
class Sum
{
    public string text1;
    public string text2;

    public string ReturnText
    {
         return text1 + text2;
    }
}

コンストラクタ

インスタンスを生成する際に引数で情報を受けてれるようにする

program.cs
Sum sum = new Sum("こんにちは" ,"皆さ~ん");

string text3 = sum.ReturnText();
console.WriteLine(text3);
classSum.cs
class Sum
{
    public string text1;
    public string text2;

    public Sum(string textA ,string textB)
    {
         this.text1 = textA;
         this.text2 = textB;
    }

    public string ReturnText
    {
         return text1 + text2;
    }
}

コンストラクタは戻り値を持たない為voidの記述もいらない。
public + クラス名とする事でコンストラクタとなる。

変数text1,text2はコンストラクタでは使えない。
宣言した変数、メソッド(関数)はコードブロック内でしか使えない。
しかし、this.変数名とする事で同一クラス内にあるクラス変数、メソッド(関数)を使う事ができる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0