[英]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.