您的位置:首页 > 编程语言 > C#

C# abstract的一点理解

2017-10-02 10:52 218 查看
首先我先试运行了微软给的示例程序:

abstract class ShapesClass
{
abstract public int Area();
}
class Square : ShapesClass
{
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());
}

interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}

}
// Output: Area of the square = 144

然后改为已经学过的简单形式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
//abstract class ShapesClass
//{
// abstract public int Area();
//}
class Square //: ShapesClass
{
int side = 0;

public Square(int n)
{
side = n;
}
// Area method is required to avoid
// a compile-time error.
//public override int Area()
public int Area()
{
return side * side;
}

static void Main()
{
Square sq = new Square(12);
Console.WriteLine("Area of the square = {0}", sq.Area());
Console.ReadKey();
}

interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}

}
}
// Output: Area of the square = 144可以看出,两者结果是相同的,也就是说abstract类并没有实际上创新类的运行方式,只是进行改进方便某一方面的编程。

微软官方给的解释是:抽象类的用途是提供一个可供多个派生类共享的通用基类定义。 例如,类库可以定义一个抽象类,将其用作多个类库函数的参数,并要求使用该库的程序员通过创建派生类来提供自己的类实现。
http://www.cnblogs.com/acetaohai123/p/7619779.html
附上一篇相关博客。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: