我必须编写简单的音乐播放器,它是覆盖方法的练习。我必须提供艺术家和标题名称,以及那首歌的音乐类型。
我有类的音乐类和一个基类Music
,现在我正在寻找任何解决方法,如何创建像这样的对象的最简单方法:
Music song = new Rock(artist, title);
Music song = new Classic(artist, title);
并将它们放在一个List<Music>
。
提前谢谢
答案 0 :(得分:0)
您可以尝试使用集合初始值设定项,以便创建List<Music>
:
var songs = new List<Music>
{
new Rock(artist, title),
new Classic(artist, title)
};
答案 1 :(得分:0)
如果你想要一些控制台阅读和播放歌曲的方法,你可以这样做。
public class Music {
public string Artist { get; set; }
public string Title { get; set; }
public Music(string artist, string title) {
Artist = artist;
Title = title;
}
public void play(string song) {
Console.WriteLine(song);
}
}
public class Rock : Music
{
public Rock(string artist, string title) : base(artist, title)
{
}
}
public class Classic : Music
{
public Classic(string artist, string title) : base(artist, title)
{
}
}
class Program
{
static void Main(string[] args)
{
Music song1 = new Rock("ac-dc", "highway to hell");
Music song2 = new Classic("elvis presley", "love me tender");
List<Music> list = new List<Music>();
list.Add(song1);
list.Add(song2);
Console.WriteLine(list[0].Artist +", " + list[0].Title);
Console.WriteLine(list[1].Artist + ", " + list[1].Title);
string a = Console.ReadLine(); // just type "yeah" or whatever
song1.play(a);
song1.play(a);
song1.play(a);
song1.play(a);
Console.ReadLine();
}
}