【问题标题】:How to know whether it is abstraction or inheritance by viewing the code如何通过查看代码知道是抽象还是继承
【发布时间】:2013-11-28 12:16:17
【问题描述】:

我对 c# 用于抽象和继承的方式有点困惑。 例如:抽象类看起来像

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

那么如何区分呢?

【问题讨论】:

  • 查看父类,看是否抽象
  • 这不是非此即彼的情况。两者都是继承的例子。在第一种情况下,基类是抽象的。在第二种情况下,基类不是抽象的。抽象类明确声明为这样(即:使用abstract 关键字)。还有什么好说的?

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


【解决方案1】:

由于你不能实例化一个抽象类,它需要子类实现方法。第二个样本,是一个简单的继承样本。

ChangeRequest 将具有WorkItem 的所有属性和方法(在这种情况下作为基类)。如果要覆盖某些属性或方法,则必须在 Workitem 类中将其声明为 virtual

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这不是答案,只是一个链接。像这样的事情应该作为评论留下。
    • OP 并没有问两者之间的区别是什么。此外,此处不接受仅链接的答案,因为该链接可能会中断,从而使您的答案无用。如果有的话,这个答案会更适合作为评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2011-04-22
    • 2017-09-04
    • 2016-01-07
    • 1970-01-01
    相关资源
    最近更新 更多