How do i overload a constuctor method so i don't have to provide a value for it
本问题已经有最佳答案,请猛点这里访问。
我在网上去过很多地方,但找不到任何能很好地解释重载构造函数的地方。我正寻求一些指导
我必须在我的Song类中重载构造器,以允许在不提供copiessold值的情况下创建歌曲。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Song { string name; string artist; int copiesSold; public Song(string name, string artist, int copiesSold) { this.name = name; this.artist = artist; this.copiesSold = copiesSold; } public Song() { } public string GetArtist() { return artist; } public string GetDetails() { return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},"; } public string GetCertification() { if (copiesSold < 200000) { return null; } if (copiesSold < 400000) { return"Silver"; } if (copiesSold < 600000) { return"Gold"; } return"Platinum"; |
同一类的构造函数的调用必须由该关键字执行,如下例所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Song { public string name; string artist; int copiesSold; public Song(string name, string artist, int copiesSold) { this.name = name; this.artist = artist; this.copiesSold = copiesSold; } public Song():this("my_name","my_artist",1000) { } } |