如何通过查看代码来了解它是抽象还是继承

时间:2013-11-28 12:16:18

标签: c# c#-4.0 inheritance abstract-class

我对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; }
}

那么如何区分?

2 个答案:

答案 0 :(得分:1)

由于您无法实例化抽象类,因此需要子类实现方法。第二个样本是一个简单的遗传样本。

ChangeRequest将拥有WorkItem的所有属性和方法(在本例中为基类)。如果要覆盖某些属性或方法,则必须在virtual类中将其声明为Workitem

答案 1 :(得分:-2)

您可以浏览以下网站。你会得到一个清晰的想法

http://www.codeproject.com/Questions/378919/Exact-difference-between-Inheritance-and-Abstracti