簡體   English   中英

C#數據結構-引用調用對象屬性的最佳方法是什么?

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

這就是當前數據的結構。 我遇到的問題是我不確定

  1. 如果我正確地構造這個
  2. 在何處放置findB函數。 findB函數最初在類A中,但類A是調用對象。

任何幫助將不勝感激。 我是新來詢問有關代碼的問題的人,所以請多多包涵。

正在由對象/聚合通常知道他們的父母。 所以,我不會說您的結構非常好。

也就是說,在您的示例中, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM