2013-08-06 99 views
1

我在一類下面的構造函數稱爲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

從派生類?或者完全從一個單獨的課程? – AlliterativeAlice

+5

在第一個構造函數中,您在設置'mHome'之前設置了'mHome.X'。 – cadrell0

+0

它爲一個單獨的類 – user2657462

回答

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

構造函數在您新創建類的實例時調用。例如,

BaseRobot _robot = new BaseRobot(1); 

它調用接受int參數的構造函數。