自身内类的对象
本文关键字:对象 | 更新日期: 2023-09-27 17:56:19
嘿,我在想我是否可以制作一个类的实例......
我的问题是我为行星及其卫星创建3D球体,我将其数据保存在对象中。我将参数传递给我的行星类的构造函数,用于"大小"轨道半径"纹理"旋转速度"等。我必须为行星的月球制作另一个类,这是月球类的精确复制品。
我在想我是否可以在它里面制作类对象。为要创建的自身对象列表''数组传递一个参数,就像地球一样,我将传递"1"以创建一个卫星,并且由于月球将具有相同的构造函数,我将传递"0"表示没有月亮的卫星。来创建。
像这样的东西
class Planet
{
Model u_sphere;
Texture2D u_texture;
//Other data members
List<Planet> Moons = new List<Planet>();
Planet()
{
//Default Constructor
}
//Overloaded'Custom Constructor
Planet(Model m, Texture2D t, int moon_count)
{
u_sphere = m;
u_texture = t;
while(moon_count > 0)
{
Model moon_sphere = LoadMesh("moon.x");
Texture2D u_texture = LoadTexture("moon.bmp");
Planet temp = new Planet(moon_sphere,moon_texture,0);
Moons.Add(temp);
moon_count--;
}
}
//Others Getters & Setters
}
有什么可能吗?
或者解决此类问题的最佳实践''方法是什么?
p.s 我正在使用 C# 和 Microsoft X.N.A 框架
是的,为什么不呢?但是,您可能希望创建一个类型 CelestialBody
的基类,Planet
类和Moon
类都将从该基类中独立。而且您不必将Planet
的Moon
传递到构造函数中,但您可以Planet
如下所示:
public class Moon : CelestialBody
{
//Moon-only properties here.
}
public class Planet : CelestialBody
{
//Planet-only properties here.
public List<Moon> Moons { get; set; }
}
然后像这样添加Moon
:
myPlanet.Moons.Add(new Moon(...));
例如,抽象掉一些信息,因为Moon
不是Planet
。
一种更面向对象的方法可以将任何特定于月球的代码分离到自己的类中。 这可能有助于使代码在变大时更有条理。 我知道月亮不是真正的行星,但谁在乎呢?
然而,这样做的缺点是你现在限制了你的遗产选项,所以这是一个你必须考虑的设计决策。
class Planet
{
Model u_sphere;
Texture2D u_texture;
List<Planet> Moons = new List<Planet>();
Planet(){}
Planet(Model m, Texture2D t, int moon_count)
{
u_sphere = m;
u_texture = t;
while(moon_count > 0)
{
Planet temp = new Moon();
Moons.Add(temp);
moon_count--;
}
}
}
class Moon : Planet
{
Moon()
{
u_sphere = LoadMesh("moon.x");
u_texture = LoadTexture("moon.bmp");
}
}
当然。您只是再次重用该类。请记住,类的某些属性可能不再适用(没有月亮的月亮这样的东西,是吗?
您可能希望添加一个传递布尔值 isChild 的构造函数。这样,嵌套的子项就可以意识到它确实是一个子项。
你得到的东西似乎已经很准确了。一种可能的改进是创建一个名为 Moon
的新类,并让它继承自 Planet
。 这样,您可以为Moon
添加其他属性/功能,例如存储对拥有Planet
的引用。
当然,这是有效的代码。
不过,由于其他原因,这种类型的设计可能会有问题。为什么一个行星类会知道如何创建其他行星实例等。如果创造行星的逻辑在类 imo 之外,那就更清楚了。
虽然你的代码还可以,但看起来它有点太接近一个 infanite 循环,不符合我的口味。 如果您将 0 更改为 1,那么 BANG! 使其更健壮的一种方法是创建一个额外的构造函数并链接它们。 这样就没有递归了。
Planet(Model m, Texture2D t, int moon_count) : this(m, t)
{
while(moon_count > 0)
{
Model moon_sphere = LoadMesh("moon.x");
Texture2D u_texture = LoadTexture("moon.bmp");
Planet temp = new Planet(moon_sphere, moon_texture);
Moons.Add(temp);
moon_count--;
}
}
Planet(Model m, Texture2D t)
{
u_sphere = m;
u_texture = t;
}