繁体   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