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);
}
}