【发布时间】:2021-07-05 02:34:30
【问题描述】:
我只是在为我的编码课程做一些练习。我刚开始抽象,所以对我来说还是有点困惑。我有这段代码,到目前为止我已经设法为常规属性赋值。我想通过虚拟方法运行一个抽象属性,并最终将结果分配给该属性。抽象方法应该在第二个派生类而不是第一个派生类上被覆盖。
现在的结果是,两个派生类的 BPM 属性的值都是 0,尽管我不确定为什么。
public abstract class Music
{
protected string genre;
protected int bpm;
public string Genre //property
{
get
{
return genre;
}
set
{
genre = value;
}
}
public int Bpm //abstract property
{
get;
set;
}
public virtual int BPM(int b) //virtual method
{
this.bpm = b;
return b;
}
public Music(string genre, int bpm)
{
this.genre = genre;
this.bpm = BPM(bpm);
}
}
public class Techno : Music
{
public Techno(string genre, int bpm) : base(genre, bpm) { }
}
public class Dubstep : Music
{
public override int BPM(int b)
{
return base.BPM(b) / 2;
}
public Dubstep(string genre, int bpm) : base(genre,bpm) { }
}
//PROGRAM-------------------------------------------------------------
class Program
{
static void Main()
{
Techno t = new Techno("Techno", 130);
Dubstep d = new Dubstep("Dubstep", 140);
Console.WriteLine(t.Genre + " " + d.Genre);
Console.WriteLine(t.Bpm + " " + d.Bpm);
}
}
【问题讨论】:
-
Bpm不是抽象属性(它没有被声明为abstract);它是抽象类中的常规属性。 -
而
protected int bpm;与public int Bpm { get; set; }无关,只是名称相似。 -
@Llama 哦!好的我明白了。那么我猜我在派生类中引用属性的方式也必须改变?
标签: c# inheritance abstraction