2013-02-10 59 views
1
public class myWorld 
{ 
    public int data; 
    public void ChangeData() 
    { 
     data = 10; 
    } 
} 

public class myRobot : myWorld 
{ 
    public void robotChangesData() 
    { 
     //how can i make the robot change the data in world? 
    } 
} 

我瞭解(或多或少),這不應該做這樣了,一直問一千遍,因爲每一個變化,應通過方法 - 但:基類變量/直接訪問對象的C#

如果我們待在世界和機器人的例子中,後面我想要有一個像這樣的機器人的方法:robot.MoveBox(25) 其中機器人必須有權訪問世界,一個對象框並更新繪圖對象(網格,形狀等) 我現在唯一能拿出來的,就是傳遞機器人的每種方法(如moveboxrobotChangesData)全世界+方塊+繪圖s凝灰岩作爲'參考',他可以改變它然後.. 但每種方法看起來像robot.MoveBox(25, ref myworldObject, ref myworldBoxes,ref etc etc)

這真的是正確的路要走嗎?還是我錯過了重要的事情?

+3

一個'Robot'是不是「世界」。你濫用繼承。 – SLaks 2013-02-10 14:54:09

+0

你誤解了'ref'。 http://www.yoda.arachsys.com/csharp/parameters.html – SLaks 2013-02-10 14:55:03

回答

0

也許一個例子有助於:

你的機器人基類

public class RobotBase 
{ 
    protected int data; 

    // Reference to the world 
    protected World _world; 

    public RobotBase(World world) 
    { 
     _world = world; 
    } 

    public void ChangeData() 
    { 
     data = 10; 
    } 
} 

你的機器人類:

public class Robot : RobotBase 
{ 
    public Robot(World world) : base(world) 
    {} 

    public void RobotChangesData() 
    { 
     //Change data in base 
     data = 20; 

     // Change data in world, the object is passed by reference, no need for further "ref" declarations 
     _world.Terminate(); 
    } 
} 

你的世界級:

public class World 
{ 
    public void Terminate() 
    { 
     // terminate world! noooess! 
    } 
} 
+0

我想我開始明白了..謝謝! – atair 2013-02-10 15:50:13

+0

很酷,如果現在沒有別的東西,請接受答案,以便其他人知道您的問題已解決。乾杯 – bas 2013-02-10 15:57:17

0

你不要把它作爲參考。

爲您的模型創建一個類/對象表示,並且只將它作爲參數傳遞給您的機器人。

暴露的方法應該對應於他可以改變的varoables。

不要對每個世界/模型狀態變量使用refs和outs。