using System;
namespace Inherit
{
public class Baseclass
{
public void Sum(int x, int y) //基类中定义的方法
{
int result = x + y;
Console.WriteLine("基类中方法计算两数和:{0}+{1}={2}",x,y,result);
}
}
public class Derivedclass : Baseclass
{
public void Change(int x,int y) //派生类中定义的方法
{
int temp;
Console.WriteLine("派生类中方法交换两数:");
Console.WriteLine("交换前:x={0} y={1}",x,y);
temp = x; x = y; y = temp;
Console.WriteLine("交换后:x={0} y={1}", x, y);
}
}
class program
{
static void Main(string[] args)
{
Derivedclass dc = new Derivedclass();
dc.Sum(5,6);
Console.WriteLine();
dc.Change(5,6);
}
}
}
结果:
基类中方法计算两数和:5+6=11
派生类中方法交换两数:
交换前:x=5 y=6
交换后:x=6 y=5
基类中定义了方法Sum(),在派生类中定义方法Change()。分别用于完成两数求和和交换两数位置的功能。在
主函数中创建了派生类对象,并利用派生类分别调用这两个方法。有结果可看到,基类中方法被派生类继承,
可在派生类的对象引用。当然这种引用也跟访问修饰符相关,因为方法被public修饰。
using System;
namespace Attribute
{
class TimePeriod
{
private double seconds;
public double hours
{
get { return seconds;}
set {seconds= value*3600;}
}
}
class Program
{
static void Main(string[] args)
{
TimePeriod t= new TimePeriod();
t.hours=24;
Console.WriteLine("共有" + t.hours + "秒");
}
}
}
using System;
namespace XCon
{
class XConst
{
// public int x,y;
public XConst(int x,int y)
{
Console.WriteLine("x={0},y={1}",x,y);
}
~XConst()
{
Console.WriteLine("Destructed {0}",this);
}
}
class program
{
static void Main(string[] args)
{
XConst sd= new XConst(100,200);
Console.WriteLine();
Console.WriteLine();
}
}
}
结果:x=100,y=200
Destructed XCon.XConst