C#基础学习之继承和扩展方法
类的继承目的主要实现代码的复用,并且可以扩展已经编写的代码的功能。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace classproj
{
class Program
{
public abstract class Sharp
{
//----properties
public double length { get;set; }
public double width { get; set; }
//----methods----
public virtual double perimeter()
{
return 2 * (this.length + this.width);
}
public abstract double Area();//抽象方法只能在抽象类中定义,没有实现函数,只能在派生类中重载
}
public class rectangle : Sharp
{
//override abstract class function
public override double Area()
{
//return this.length * this.width;
return base.length * base.width; //可以使用base关键字,其表示派生类的父类而非根类
}
}
public class circle : Sharp
{
//override abstract class function
public override double Area()
{
return Math.PI * Math.Pow(this.length / 2, 2);
}
public override double perimeter()
{
return Math.PI * (this.length);
}
}
static void Main(string[] args)
{
// Sharp s = new Sharp();抽象类不能实例化,只能继承
rectangle r = new rectangle();
circle c = new circle();
c.length = 10;
r.length = 20;
r.width = 30;
Console.WriteLine("rectangle'sperimeter: " + r.perimeter());
Console.WriteLine("rectangle'sperimeter: " + r.Area());
Console.WriteLine("circle'sperimeter: "+c.perimeter());
Console.WriteLine("circle'Area: " + c.Area());
}
}
}
当然还有密封类的方法,某个类不需要被继承可以使用关键字sealed密封这个类,注意:密封的类不能包括虚方法。。。
重载方法:类中有多个具有相同名称和不同参数的方法,当然可以使用泛型,这样更简便。。。
我们知道要增加类的功能,我们需要派生新类C#3.0新增了扩展方法例如向rectangle类中添加diagonal(),可以定义一个静态类并在该类中定义扩展方法(静态的)
public static class mathodex
{
public static double diagonal(this rectangle rect)
{
//code
}
}
这样就可以使用rectangle类对象调用diagonal()函数了。。。
继承的不同关键字
new :隐藏具有相同签名的继承方法
static :属于类型自身而不属于特定对象的成员,也就是说只能用类名来访问而不是对象来访问
virtual :派生类可以重写的方法
abstract :提供方法和类的签名,但不提供任何实现
override:重写继承的虚方法和抽象方法
sealed:派生类不可以重写的方法,其他类不可以继承
extern:“外部”方法
posted on 2012-05-21 09:34 Perfect_lsh 阅读(366) 评论(0) 收藏 举报
浙公网安备 33010602011771号