2017-10-13 4 views
-2

こんにちは私はC#コースをやっていて、コンストラクタ呼び出しの対象を理解できません。私はこれでエラーが発生し、ビデオを見ているが、私はそれを動作させることができない、私はエラーを取得し続けている: "E2.Student.Student(文字列、文字列)は自分自身を呼び出すことはできません"コンストラクタコールin c#クラス

私は2つのパラメータを持つコンストラクタを作成するこのエラーは、このコンストラクタを作成しようとしている2つのパラメータが4つのパラメータを持つコンストラクタから継承していることを理解しているので、私の学習コンテンツから

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace E2 
{ 
    class Student 
    { 
     string fullName; 
     string course; 
     string email; 
     string phonenr; 
     enumUniversity university; 
     enumSubject subject; 

     public Student() 
     { 
     } 

     public Student(string fullname,string course) : this (fullname,course) =======>THIS IS WHERE I GET THE ERROR 
     { 
     } 

     public Student(string fullname, string course, string email, string phonenr, enumUniversity university, enumSubject subject) 
     { 
      this.fullName = fullname; 
      this.course = course; 
      this.email = email; 
      this.phonenr = phonenr; 
      this.university = university; 
      this.subject = subject; 
     } 

     public void PrintInfo() 
     { 
      Console.WriteLine("Name: {0} Course {1} email {2} phonenr {3} univ {4} subject {5}", fullName, course, email, phonenr, university, subject); 
     } 
    } 
} 

例:

public Dog(string name) 
: this(name, 1) // Constructor call 
{ 
} 
// Two parameters 
public Dog(string name, int age) 
: this(name, age, 0.3) // Constructor call 
{ 
} 
// Three parameters 
public Dog(string name, int age, double length) 
: this(name, age, length, new Collar()) // Constructor call 
{ 
} 
// Four parameters 
public Dog(string name, int age, double length, Collar collar) 
{ 
this.name = name; 
this.age = age; 
this.length = length; 
this.collar = collar; 
} 
+3

2つのパラメータコンストラクタが6つのパラメータコンストラクタに依存することを意図している場合、*どの値*を 'email'、' phoner'などに使用する必要がありますか? –

+1

デフォルト値を指定します:this(fullname、course、 "default email"、 "default phone"、university.Val、subject.Val) – mm8

+0

現在、2つのパラメータを持つコンストラクタで、2つのパラメータ(それ自身)を持つコンストラクタを呼び出します。他のコンストラクターを呼び出すためのパラメーターを追加します。 – FCin

答えて

1

あなたはコンストラクタがctorの連鎖を使用して自分自身を呼び出してみましょう。このオフコースは、世界が無限ループにつながるため不可能です:)

これを行う方法は、他のすべての引数を指定してコンストラクタを呼び出す必要があります。

 public Student() : this(string.Empty, string.Empty) 
     { 
     } 

     public Student(string fullname,string course) 
      : this (fullname,course, string.Empty, string.Empty, default(enumUniversity), default(enumSubject)) 
     { 
     } 

     public Student(string fullname, string course, string email, string phonenr, enumUniversity university, enumSubject subject) 
     { 
      this.fullName = fullname; 
      this.course = course; 
      this.email = email; 
      this.phonenr = phonenr; 
      this.university = university; 
      this.subject = subject; 
     } 
+0

よろしくお願いいたします。正しい答えをできるだけ早く受け入れます。 – Wilest