我在名为BaseRobot
的类中有以下构造函数:
public BaseRobot(int aId)
{
mId = aId;
mHome.X = 0;
mHome = new Point(0, 0);
mPosition = mHome;
}
public BaseRobot(int aId, int aX, int aY)
{
mId = aId;
mHome = new Point(aX, aY);
mPosition = mHome;
}
如何在另一个类中调用BaseRobot
构造函数?
答案 0 :(得分:8)
var robot = new BaseRobot(7); //calls the first constructor
var robot2 = new BaseRobot(7, 8, 9); //calls the second
如果要创建派生类
public class FancyRobot : BaseRobot
{
public FancyRobot() : base(7, 8, 9)
{ // calls the 2nd constructor on the base class
Console.WriteLine("Created a fancy robot with defaults");
}
}
//this calls the FancyRobot default constructor, which in-turn calls the BaseRobot constructor
var fancy = new FancyRobot();
您永远不会直接调用构造函数,代码仅在实例化对象时执行。如果要从另一个类设置对象的属性,可以创建设置类成员变量的公共属性或方法。
public class AnotherRobotType
{
public string Model {get;set;} // public property
private int _make; // private property
public AnotherRobotType() {
}
/* these are methods that set the object's internal state
this is a contrived example, b/c in reality you would use a auto-property (like Model) for this */
public int getMake() { return _make; }
public void setMake(int val) { _make = val; }
}
public static class Program
{
public static void Main(string[] args)
{
// setting object properties from another class
var robot = new AnotherRobotType();
robot.Model = "bender";
robot.setMake(1000);
}
}
答案 1 :(得分:1)
当您新创建类的实例时,将调用构造函数。例如,
BaseRobot _robot = new BaseRobot(1);
调用接受int参数的构造函数。