这个问题用继承就对啦~ ,看完还不清楚去看看继承相关教程
//父类
public class Parent
{
//父亲类的构造函数test,具体什么功能自己写
public void test() { }
}
//子类1继承父类,(子类:父类)就是继承的语法了
public class Son1:Father{}
//子类2继承父亲类
public class Son2:Father{}
然后就是在主函数中调用啦~
static void Main(string[] args)
{
//创建Son1类的实例
Son1 s = new Son1();
//创建Son2类的实例
Son2 s2 = new Son2();
//继承后子类就有父类中的test(){}构造函数了,可以直接引用
s.test();
s2.test();
} 作者: 许庭洲 时间: 2013-3-2 19:23
using System;
calss Vehicle//定义汽车类
{
public int wheels;//公有成员:轮子个数
protected float weight; //保护成员:重量
public Vehicle(){;}
public Vehicle(int w,float g)
{
wheels = w;
weight = g;
}
public void Show()
{
Console.WriteLine("the wheel of vehicle is :{0}",wheels);
Console.WriteLine("the weight of vehicle is :{0}",weight);
}
};
class train //定义火车类
{
public int num;//公有成员:车厢数目
private int passengers;//私有成员:乘客数
private float weight;//私有成员:重量
public Train(){;}
public Trian(int n,int p,float w)
{
num = n;
passengers = p;
weight = w;
}
public void Show()
{
Console.WriteLine("the num of train is :{0}",num );
Console.WriteLine("the weight of train is :{0}",weight);
Console.WriteLine("the Passengers of train is :{0}",Passengers );
}
}
class Car:Vehicle//定义轿车类
{
int passengers;//私有成员:乘客数
public Car(int w,float g,int p):base(w,g)
{
wheels = w;
weight = g;
passengers = p;
}
new public void Show()
{
Console.WriteLine("the wheel of car :{0}",num );
Console.WriteLine("the weight of car is :{0}",weight);
Console.WriteLine("the Passengers of car is :{0}",Passengers );
}
}
class Test
{
public static void Main(){
Vehicle v1 = new Vehicle(4,5);
Train t1 = new Trian();
Trian t2 = new Trian(10,100,100);
Car c1 = new Car(4,2,4);
v1.show();
t1.show();
t2.show();
c1.show();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
程序的运行结果为:
the wheel of vehicle is:0
the weight of vehicle is 0
the num of train is:0
the weight of train is:0
the Passengers of train is:0
the num of trian is:10
the weight of train is:100
the Passengers of trin is:100
the wheel of car is:4
the weight of car is:2
the Passebger of car is:4
作者: 康晓璞 时间: 2013-3-2 20:03
要实现子类调用父类的构造方法,最重要的是在子类实例化时,使用base关键字
我们知道,子类实现实例化,首先需要将父类实现实例化,父类再实现基类实例化,
这样我们再实例化子类通过向父类传递一些构造参数,就可以在父类的构造函数内给父类的属性赋值,
由于子类和父类是继承关系,所有子类就继承了父类的所有的属性
简单的例子
public class BaseClass
{
/// <summary>
/// 定义自动实现的属性
/// </summary>
public string FirstName { get; set; }
public BaseClass(string firstName)
{
FirstName = firstName;
}
}
public class DerivedClass:BaseClass
{
public DerivedClass(string firstName):base(firstName)//向父类的构造函数传递firstName参数
{ }
}
调用;
DerivedClass d = new DerivedClass("Kang");