只允许单继承,多继承可以由接口来实现,继承是可以传递的,类可以定义虚方法、虚属性、虚索引指示器,而派生类能重写这些成员,以事项面向对象编程中的多态
1.类的继承
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class student
{
private string xh;
private string name;
public student(string m_xh, string m_name)
{
xh = m_xh;
name = m_name;
}
public virtual void display()
{
Console.WriteLine("学号:{0}", xh);
Console.WriteLine("姓名:{0}", name);
}
}
class good_student : student //继承student类
{
private decimal bursary = 0.0m;
public good_student(string m_xh, string m_name, decimal m_bursary)
: base(m_xh, m_name)
{
bursary = m_bursary;
}
public override void display()
{
base.display();
Console.WriteLine("奖学金:{0}", bursary);
}
}
public class basetest
{
public static void Main()
{
good_student gs = new good_student("1001","赵六",1200.0m);
gs.display();
Console.Read();
}
}
2.接口的继承(接口里的方法必须在派生类中实现)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
interface IA //声明接口
{
float length(); //声明抽象成员(成员中不包含可执行代码)
float width();
}
interface IB //声明接口
{
float length(); //声明抽象成员(成员中不包含可执行代码)
float width();
}
class box : IA, IB
{
float Iinches;
float Winches;
public box(float length, float width) //构造函数
{
Iinches = length;
Winches = width;
}
float IA.length() //实现接口的抽象方法
{
return Iinches;
}
float IA.width()
{
return Winches;
}
float IB.length()
{
return Iinches * 0.178f;
}
float IB.width()
{
return Winches * 1.78f;
}
}
public class maintest
{
public static void Main()
{
box b = new box(123.0f, 456.123f);
IA ia = (IA)b; //显式转换创建实例对象
IB ib = (IB)b;
Console.WriteLine("inches:");
Console.WriteLine("\t\t length:{0}", ia.length());
Console.WriteLine("\t\t width:{0}", ia.width());
Console.WriteLine("metrics");
Console.WriteLine("\t\t length:{0}", ib.length());
Console.WriteLine("\t\t width:{0}", ib.width());
Console.Read();
}
}