【www.gdgbn.com--其他相关】

一、抽象类:
  抽象类是特殊的类,只是不能被实例化;除此以外,具有类的其他特性;重要的是抽象类可以包括抽象方法,这是普通类所不能的。抽象方法只能声明于抽象类中,且不包含任何实现,派生类必须覆盖它们。另外,抽象类可以派生自一个抽象类,可以覆盖基类的抽象方法也可以不覆盖,如果不覆盖,则其派生类必须覆盖它们。

using system;
using system.collections.generic;
using system.text;
using system.threading;

namespace apptest
{
class demo_abstract
{
static void main(string[] args)
{
double len = 2.5;
double wid = 3.0;
double rad = 4.1;
rectangle arect = new rectangle();
arect.length = len;
arect.width = wid;
circle acirc = new circle(rad);
console.writeline("area of rect is:{0}", arect.area());
console.writeline("area of circ is:{0}", acirc.area());

            //体现 abstract 的优势,不用的实例获取不同的功能
//结果与 rectangle实例的一样
shape shape = new rectangle(len, wid);
console.writeline("area of shape is:{0}", shape.area());

            thread.sleep(3 * 1000); //暂停3秒看结果
}
}

    //图形
abstract class shape                //抽象基类,不可实例化
{
public const double pi = 3.14;    //常量
protected double x, y;            //私有,可继承变量

        public shape()                    //默认构造函数
{
x = y = 0;
}
public shape(double x, double y)    //带参数构造函数
{
this.x = x;
this.y = y;
}
public abstract double area();    //抽象方法,需重载
}

    //方形
class rectangle : shape
{
public rectangle() : base() { }
public rectangle(double x, double y) : base(x, y) { }//使用基类构造函数
public override double area()    //函数重载
{
return (x * y);
}
public double length    //属性:矩形长度
{
get
{
return x;
}
set
{
if (value > 0) { x = value; }
}
}
public double width        //属性:矩形宽度
{
get
{
return y;
}
set
{
if (value > 0) { y = value; }
}
}

    }

    //椭圆
class ellips教程e : shape
{
public ellipse(double x, double y) : base(x, y) { }//使用基类shape的构造函数
public override double area()    //函数重载
{
return pi * x * y;
}
}

    //圆形
class circle : ellipse
{
public circle(double r) : base(r, 0) { }    //使用基类ellipse的构造函数
public override double area()    //函数重载
{
return pi * x * x;
}
}

}

二、接口:
  接口是引用类型的,类似于类,和抽象类的相似之处有三点:
  1、不能实例化;
  2、包含未实现的方法声明;
  3、派生类必须实现未实现的方法,抽象类是抽象方法,接口则是所有成员(不仅是方法包括其他成员);
  另外,接口有如下特性:
  接口除了可以包含方法之外,还可以包含属性、索引器、事件,而且这些成员都被定义为公有的。除此之外,不能包含任何其他的成员,例如:常量、域、构造函数、析构函数、静态成员。一个类可以直接继承多个接口,但只能直接继承一个类(包括抽象类)。

 interface isampleinterface
{
    void samplemethod();
}

class implementationclass : isampleinterface
{
    // explicit interface member implementation:
    void isampleinterface.samplemethod()
    {
        // method implementation.
    }

    static void main()
    {
        // declare an interface instance.
        isampleinterface obj = new implementationclass();

        // call the member.
        obj.samplemethod();
    }
}

本文来源:http://www.gdgbn.com/asp/29170/