Udfordring: Konstruktører
En simpel klasse kaldet Dog er givet. Opret en konstruktør, som tager argumenterne name, breed, age og initialiserer felterne med værdierne fra argumenterne.
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(); } }
For at tildele argumentværdierne til felterne uden at forårsage fejl, skal du bruge this-operatoren, da argumenterne har samme navn som felterne.
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(); } }
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
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?
Fantastisk!
Completion rate forbedret til 2.04
Udfordring: Konstruktører
Stryg for at vise menuen
En simpel klasse kaldet Dog er givet. Opret en konstruktør, som tager argumenterne name, breed, age og initialiserer felterne med værdierne fra argumenterne.
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(); } }
For at tildele argumentværdierne til felterne uden at forårsage fejl, skal du bruge this-operatoren, da argumenterne har samme navn som felterne.
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(); } }
Tak for dine kommentarer!