0

我在一个名为的类中有以下构造函数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在另一个类中调用构造函数?

4

2 回答 2

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);
    }
}
于 2013-08-06T15:52:45.210 回答
1

当您新创建类的实例时,将调用构造函数。例子,

BaseRobot _robot = new BaseRobot(1);

它调用接受 int 参数的构造函数。

于 2013-08-06T15:53:21.670 回答