Konstruktory: książka z trzema konstruktorami
Klasy i obiekty - Podstawy C# (csharp)
Klasa
Book ma trzy konstruktory połączone łańcuchem : this(...): bezparametrowy i jednoparametrowy uzupełniają brakujące dane wartościami domyślnymi i przekazują pracę do pełnego konstruktora. W C# często zamiast kilku konstruktorów stosuje się parametry domyślne (int year = 0) i argumenty nazwane (year: 1999) - pokazuje to metoda Describe.using System;
class Book
{
private string title;
private string author;
private int year;
public Book() : this("Bez tytułu", "Nieznany", 0)
{
}
public Book(string title) : this(title, "Nieznany", 0)
{
}
public Book(string title, string author, int year)
{
this.title = title;
this.author = author;
this.year = year;
}
public void DisplayInfo()
{
string yearText = year > 0 ? year.ToString() : "brak danych";
Console.WriteLine($"\"{title}\", autor: {author}, rok: {yearText}");
}
}
class Program
{
static string Describe(string title, string author = "Nieznany", int year = 0)
{
return $"{title} / {author} / {year}";
}
static void Main(string[] args)
{
new Book().DisplayInfo();
new Book("Pan Tadeusz").DisplayInfo();
new Book("Lalka", "Bolesław Prus", 1890).DisplayInfo();
Console.WriteLine(Describe("Quo vadis"));
Console.WriteLine(Describe("Quo vadis", year: 1896));
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.