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?
}
}我理解(或多或少)不应该这样做,并且已经被问了一千次,因为每个更改都应该通过方法-但是:
如果我们停留在世界和机器人的例子上,稍后我想要有一个机器人的方法,比如:robot.MoveBox(25),其中机器人必须访问世界,一个对象框,并对绘制对象(网格,形状等)进行更新。我现在唯一能想到的,就是把机器人的每一种方法(像movebox或robotChangesData)都传给整个世界+方框+画东西作为'ref‘,然后他就可以改变它了。但是every方法看起来像robot.MoveBox(25, ref myworldObject, ref myworldBoxes,ref etc etc)
这真的是正确的方法吗?还是我错过了什么重要的东西?
发布于 2013-02-10 23:01:16
也许下面的例子会有所帮助:
你的机器人基类
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!
}
}发布于 2013-02-10 22:55:37
你不需要把它当做一个裁判。
为您的模型创建一个类/对象表示,并仅将其作为参数传递给您的机器人。
公开的方法应该与可以更改的变量相对应。
不要为每个世界/模型状态变量使用ref和out。
https://stackoverflow.com/questions/14798961
复制相似问题