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