Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:コンストラクター | オブジェクト指向プログラミング(OOP)イントロダクション
C#オブジェクト指向構造

bookチャレンジ:コンストラクター

メニューを表示するにはスワイプしてください

Dogというシンプルなクラスが与えられています。引数namebreedageを受け取り、それぞれのフィールドを引数の値で初期化するコンストラクタの作成。

index.cs

index.cs

copy
123456789101112131415161718192021222324
using 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

index.cs

copy
12345678910111213141516171819202122232425262728
using 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に質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  10
some-alt