基本的に私のコードは次のとおりです。コンストラクタにパラメータを渡す方法
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the name of the coursebook");
String cousebookname = Console.ReadLine();
Person p1 = new Person(String cousebookname);
p1.displayMessage();
}
}
}
public class Person
{
private String courseName;
Person(String name)
{
courseName = name;
}
public void displayMessage()
{
Console.WriteLine("The name of the course is \n{0}", courseName);
}
}
私はPersonクラスを作成し、private変数、コンストラクタ、およびメソッドとしてcourseNameを定義しました。メインクラスでは、Personオブジェクトの作成されたインスタンスを作成しました。私の理解によると、インスタンスが作成されるとすぐに、コンストラクタが初期化されます。パラメータstring coursebooknameを渡すと、 "現在のコンテキストに名前がありません"というエラーが発生します。助けてください。
'coursebookname'変数は一度しか定義できません(タイプを指定するときです)。 'Person'コンストラクタに渡すときに' String'指定を変数名の前から削除しても問題ありません。 –
'Person p1 =新しいPerson(cousebookname);'スペルを除いて。 –
そのエラーの原因は、クラスPersonが名前空間の外に存在するためです。 –