我对c#用于抽象和继承的方式有点困惑。 例如:Abstract Class看起来像
abstract class ShapesClass
{
abstract public int Area();
}
class Square : ShapesClass //USES :
{
int side = 0;
public Square(int n)
{
side = n;
}
// Area method is required to avoid
// a compile-time error.
public override int Area()
{
return side * side;
}
static void Main()
{
Square sq = new Square(12);
Console.WriteLine("Area of the square = {0}", sq.Area());
}
}
继承的看起来像,
public class WorkItem
{
private static int currentID;
//Properties.
protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }
public WorkItem()
{
ID = 0;
Title = "Default title";
Description = "Default description.";
jobLength = new TimeSpan();
}
}
public class ChangeRequest : WorkItem //This also uses :
{
protected int originalItemID { get; set; }
}
那么如何区分?
答案 0 :(得分:1)
由于您无法实例化抽象类,因此需要子类实现方法。第二个样本是一个简单的遗传样本。
ChangeRequest
将拥有WorkItem
的所有属性和方法(在本例中为基类)。如果要覆盖某些属性或方法,则必须在virtual
类中将其声明为Workitem
。
答案 1 :(得分:-2)