从另一个类调用构造函数

use*_*462 0 c# oop

我在一个名为的类中有以下构造函数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;
}
Run Code Online (Sandbox Code Playgroud)

如何BaseRobot在另一个类中调用构造函数?

Jas*_*son 8

var robot = new BaseRobot(7); //calls the first constructor
var robot2 = new BaseRobot(7, 8, 9); //calls the second
Run Code Online (Sandbox Code Playgroud)

如果要创建派生类

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(); 
Run Code Online (Sandbox Code Playgroud)

您永远不会直接调用构造函数,代码仅在实例化对象时执行.如果要从另一个类设置对象的属性,可以创建设置类成员变量的公共属性或方法.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)