简体   繁体   English

C#数据结构-引用调用对象属性的最佳方法是什么?

[英]C# data structure - what is the best way to reference a calling object's property?

My data is currently structured as follows: 我的数据目前的结构如下:

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
}

This is how the data is currently structured. 这就是当前数据的结构。 The problem I'm having is I'm not sure 我遇到的问题是我不确定

  1. If I'm structuring this properly 如果我正确地构造这个
  2. Where to place the findB function. 在何处放置findB函数。 The findB function was originally in class A, but class A is the calling object. findB函数最初在类A中,但类A是调用对象。

Any help would be greatly appreciated. 任何帮助将不胜感激。 I am new to asking questions about code, so bear with me please. 我是新来询问有关代码的问题的人,所以请多多包涵。

Objects that are being composed/aggregated usually do not know about their parents. 正在由对象/聚合通常知道他们的父母。 So no, I wouldn't say your structure is very good. 所以,我不会说您的结构非常好。

That is, in your example, C has no idea that it is being created by A and so doesn't know anything about bArray . 也就是说,在您的示例中, C 不知道它是由A创建的,因此对bArray Depending on the context, this is exactly how it should be . 取决于上下文,这正是应有的方式

Now, you could pass an A reference to C : 现在,您可以 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
    }
}

And put findB in A again. 再次将findB放在A Thats where it should go, since its the only thing that knows about bArray . 那是应该去的地方,因为它是唯一了解bArray东西。

But that tighlty couples C to A . 但是那种顽皮的将C耦合到A That might be ok in your situation, it might not. 在您的情况下可能没问题,但事实并非如此。 In general though, tight coupling like that is to be avoided. 通常,应避免那样的紧密耦合。 Without better class names/context, its impossible to say what a better design would be in your situation. 如果没有更好的类名/上下文,就无法说出您所处的环境会有更好的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM