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);
}
}
從派生類?或者完全從一個單獨的課程? – AlliterativeAlice
在第一個構造函數中,您在設置'mHome'之前設置了'mHome.X'。 – cadrell0
它爲一個單獨的類 – user2657462