Visual C#类的定义及实现方法实例解析
本文实例演示了visualC#下一个类的定义及实现方法,虽然是一个较为基础的C#代码实例,对于新手来说仍然有很好的参考价值。
具体的实例代码如下:
usingSystem;
publicclassDesk//基类Desk
{
protectedintlength;//保护成员
protectedintwidth;
protectedintheight;
//类Desk的构造函数
publicDesk()
{
length=0;
width=0;
height=0;
}
//设置Desk的信息
publicvoidSetInfo(intLen,intWid,intHei)
{
length=Len;
width=Wid;
height=Hei;
}
//打印Desk的参数信息
publicvoidShowInfo()
{
Console.WriteLine("Length={0}\tWidth={1}\tHeight={2}",length,width,height);
}
}
publicclassFurniture:Desk//定义基类Desk的派生类Furniture
{
privateintprice;//私有成员
//类Furniture的构造函数
publicFurniture()
{//这里会隐式调用基类Desk的构造函数
//Desk();//若显示调用会出现错误
price=0;
}
//重载该类的SetInfo函数
publicvoidSetInfo(intLen,intWid,intHei,intPri)
{
length=Len;
width=Wid;
height=Hei;
price=Pri;
}
//新增的函数用以设置价格
publicvoidSetPri(intPri)
{
price=Pri;
}
//重定义ShowInfo函数
publicnewvoidShowInfo()//必须加上关键字new,否则会引发一个生成错误
{
Console.WriteLine("Length={0}\tWidth={1}\tHeight={2}\tPrice={3}",length,width,height,price);
}
}
classTest
{
publicstaticvoidMain()
{
Furniturefur1=newFurniture();//隐式调用构造函数
Console.WriteLine("Fur1初始化后的值为:");
fur1.ShowInfo();//显示家具信息
fur1.SetInfo(80,50,60,350);
Console.WriteLine("Fur1设置具体信息后为:");
fur1.ShowInfo();
fur1.SetPri(288);//重置家具价格
Console.WriteLine("Fur1价格大优惠:");
fur1.ShowInfo();
}
}