コンストラクター
CoddyのC#ジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 7/70。
constructor は、オブジェクトを Create するときに実行される特別なメソッドです。オブジェクトの properties とフィールドを初期化します。
parameters なしの Default constructor
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
// デフォルトコンストラクタ
public Book()
{
Title = "Unknown";
Author = "Unknown";
}
}パラメーター付きコンストラクター
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
// パラメータ付きコンストラクタ
public Book(string title, string author)
{
Title = title;
Author = author;
}
}Constructor のオーバーロード - 複数の Constructor
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Pages { get; set; }
// 2つのパラメータを持つコンストラクタ
public Book(string title, string author)
{
Title = title;
Author = author;
Pages = 0;
}
// 3つのパラメータを持つコンストラクタ
public Book(string title, string author, int pages)
{
Title = title;
Author = author;
Pages = pages;
}
}Constructor の this を使った chaining
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Pages { get; set; }
// メインコンストラクタ
public Book(string title, string author, int pages)
{
Title = title;
Author = author;
Pages = pages;
}
// デフォルトのページ数でメインコンストラクタを呼び出す
public Book(string title, string author) : this(title, author, 0)
{
}
}異なるコンストラクターを使用したオブジェクトの作成
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);コンストラクターはクラスと同じ名前を持ち、戻り値の型を持ちません。newキーワードを使用すると自動的に実行されます。異なるパラメーターを持つ複数のコンストラクターを定義できます(オーバーロード)。
チャレンジ
中級Product class の Constructor オーバーロードと chaining を using して、3 つの Constructor を作成します:
- 3 parameters の Constructor:name、price、stock
- 2 parameters の Constructor:name と price(stock のデフォルト値は 0)
- parameters なしの Default Constructor(name = "Unknown"、price = 0、stock = 0)
コードの重複を避けるため、this を using して Constructor chaining を使用します。
自分で試してみよう
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
decimal price = decimal.Parse(Console.ReadLine());
int stock = int.Parse(Console.ReadLine());
Product product1 = new Product(name, price, stock);
Product product2 = new Product();
Product product3 = new Product("Keyboard", 79.99m);
Console.WriteLine($"Product 1: {product1.Name} - ${product1.Price} (Stock: {product1.Stock})");
Console.WriteLine($"Product 2: {product2.Name} - ${product2.Price} (Stock: {product2.Stock})");
Console.WriteLine($"Product 3: {product3.Name} - ${product3.Price} (Stock: {product3.Stock})");
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ