gpt4 book ai didi

c# - 直接访问基类变量/对象 c#

转载 作者:行者123 更新时间:2023-11-30 21:00:38 27 4
gpt4 key购买 nike

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' 然后他可以更改它..但是每个方法看起来都像 robot.MoveBox(25, ref myworldObject, ref myworldBoxes,ref etc etc)

这真的是正确的方法吗?还是我错过了什么重要的事情?

最佳答案

也许一个例子有帮助:

你的机器人基类

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!
}
}

关于c# - 直接访问基类变量/对象 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14798961/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com