Завдання: Конструктори
Дано простий клас під назвою Dog
. Створіть конструктор, який приймає аргументи name
, breed
, age
та ініціалізує поля значеннями цих аргументів.
index.cs
123456789101112131415161718192021222324using System; class Dog { public string name; public string breed; public int age; // Write constructor code below this line // Write constructor code above this line public void bark() { Console.WriteLine("Woof!"); } } public class ConsoleApp { public static void Main(string[] args) { Dog dog = new Dog("Dobby", "Dobermann", 4); dog.bark(); } }
Щоб присвоїти значення аргументів полям без виникнення помилок, необхідно використовувати оператор this
, оскільки імена аргументів збігаються з іменами полів.
index.cs
12345678910111213141516171819202122232425262728using System; class Dog { public string name; public string breed; public int age; // Write constructor code below this line public Dog(string name, string breed, int age) { this.name = name; this.breed = breed; this.age = age; } // Write constructor code above this line public void bark() { Console.WriteLine("Woof!"); } } public class ConsoleApp { public static void Main(string[] args) { Dog dog = new Dog("Dobby", "Dobermann", 4); dog.bark(); } }
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you show me how to write the constructor for the Dog class?
What does the complete Dog class look like with the constructor?
Can you explain how the `this` operator works in this context?
Awesome!
Completion rate improved to 2.04
Завдання: Конструктори
Свайпніть щоб показати меню
Дано простий клас під назвою Dog
. Створіть конструктор, який приймає аргументи name
, breed
, age
та ініціалізує поля значеннями цих аргументів.
index.cs
123456789101112131415161718192021222324using System; class Dog { public string name; public string breed; public int age; // Write constructor code below this line // Write constructor code above this line public void bark() { Console.WriteLine("Woof!"); } } public class ConsoleApp { public static void Main(string[] args) { Dog dog = new Dog("Dobby", "Dobermann", 4); dog.bark(); } }
Щоб присвоїти значення аргументів полям без виникнення помилок, необхідно використовувати оператор this
, оскільки імена аргументів збігаються з іменами полів.
index.cs
12345678910111213141516171819202122232425262728using System; class Dog { public string name; public string breed; public int age; // Write constructor code below this line public Dog(string name, string breed, int age) { this.name = name; this.breed = breed; this.age = age; } // Write constructor code above this line public void bark() { Console.WriteLine("Woof!"); } } public class ConsoleApp { public static void Main(string[] args) { Dog dog = new Dog("Dobby", "Dobermann", 4); dog.bark(); } }
Дякуємо за ваш відгук!