チャレンジ:コンストラクター
メニューを表示するにはスワイプしてください
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(); } }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 10
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 10