gpt4 book ai didi

c# - 如何控制/处理/编辑多个对象?

转载 作者:行者123 更新时间:2023-12-02 04:57:58 25 4
gpt4 key购买 nike

我对 OOP 很陌生,但我一直在玩弄 C#。一个人如何控制多个对象?

假设您有几何对象(三角形、球体等),它们都共享一个属性,即空间中的 (x,y,z) 点坐标。现在,单独移动每个不同的对象很容易。例如 rectangle.moveright();等等

但是假设我有 n 个不同的对象要作为一个组移动,有点像在桌面上标记图标/快捷方式,然后将它们作为一个组移动。

如何做到这一点?基本上你有一个控制子对象的父对象

编辑:一个更具体的例子;假设我有 10 个不同种类的对象,我只想移动其中 5 个具有某种功能的对象,稍后我想将其他 4 个对象移动到其他地方。始终作为一个群体

最佳答案

这是一个非常简单的例子。请注意,移动功能和点数并不准确,显然需要实现才能使其正常工作。

创建接口(interface)和抽象类以允许对象组的继承和多态性。

public interface IPositionable
{
void Move(int x, int y, int z);
}

public abstract class Positionable : IPositionable
{
public int x { get; set; }
public int y { get; set; }
public int z { get; set; }

public void Move( int x, int y, int z )
{
this.x += x;
this.y += y;
this.z += z;
}
}

下一步将这些应用到您将使用的形状类型中

public class Rectangle : Positionable{}
public class Triangle : Positionable{}
public class Square : Positionable{}

准备好基本部分后,您应该使用中介者模式

public class PositionMediator
{
public List<IPositionable> Group { get; set; }
public PositionMediator()
{
Group = new List<IPositionable>();
Group.Add(new Rectangle());
Group.Add(new Triangle());
Group.Add(new Square());
}
public void MoveGroup( int x, int y, int z )
{
foreach( var pos in Group )
{
pos.Move(x,y,z);
}
}
}

一旦就绪,您就可以像这样控制它:

void Main()
{
var pm = new PositionMediator();
pm.MoveGroup(1,2,3);
}

关于c# - 如何控制/处理/编辑多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620329/

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