[英]C# data structure - what is the best way to reference a calling object's property?
我的数据目前的结构如下:
class A
{
B[] bArray;
C[] cArray;
A()
{
fillB();
fillC();
}
}
class C
{
X[] x;
insertX() // adds an X element to the x array
{
X newX = new X();
newX.b = findB(searchParam); // returns the matching element from bArray
// the rest of the code adds newX to array x
}
}
class X
{
B b {get;set;} // reference to an element bArray
}
这就是当前数据的结构。 我遇到的问题是我不确定
任何帮助将不胜感激。 我是新来询问有关代码的问题的人,所以请多多包涵。
正在由对象/聚合通常不知道他们的父母。 所以,我不会说您的结构非常好。
也就是说,在您的示例中, C
不知道它是由A
创建的,因此对bArray
。 取决于上下文,这正是应有的方式 。
现在,您可以将 A
引用传递给C
:
class C
{
A parent;
X[] x;
public C(A parent)
{
this.parent = parent;
}
insertX() // adds an X element to the x array
{
X newX = new X();
newX.b = parent.findB(searchParam); // returns the matching element from bArray
// the rest of the code adds newX to array x
}
}
再次将findB
放在A
。 那是应该去的地方,因为它是唯一了解bArray
东西。
但是那种顽皮的将C
耦合到A
在您的情况下可能没问题,但事实并非如此。 通常,应避免那样的紧密耦合。 如果没有更好的类名/上下文,就无法说出您所处的环境会有更好的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.