【问题标题】:c# object compositionc# 对象组合
【发布时间】:2012-05-20 04:03:05
【问题描述】:

我有一个名为 LetterRect 的类,其中两个字段的类型为 LetterSquare。例如:

public class LetterRect : Microsoft.Xna.Framework.GameComponent
{
    private LetterSquare square1;                        
    private LetterSquare square2;
    private long indentificationNumber;
    ... other fields that are irrelevant to this question
}

我希望能够通过 square1 和 square2 获得对 LetterRect 对象的引用。我最初的解决方案是给 LetterRect 和相应的 square1 和 square2 相同的 IdentificationNumber 和一个长整数。但是,有没有办法在没有识别号的情况下访问 LetterRect?绝对不存在继承关系,它是一种组合,或“具有”关系。如果我没记错的话,Java 中有一个内部类的概念,其中内部类可以直接引用它所属的类的实例。那么,有没有更好的方法通过 square1 和 square2 来获取对 LetterRect 对象的引用呢?

感谢大家的帮助!

【问题讨论】:

  • 难道你不能在你的 LetterSquare 构造函数中添加一个 LetterRect 参数并在初始化你的方形对象时传递它吗?如果您愿意,也可以使用 DependencyInjection。
  • 将父对象传递给子对象通常不是好的设计。如果孩子需要来自父母的东西(例如,某个领域),则只需将该特定信息传递给孩子。如果您在执行此操作时遇到问题,可以向我们提供详细信息,以便我们为您提供帮助。

标签: c# oop object inner-classes object-composition


【解决方案1】:

试试这个;

public class LetterRect : Microsoft.Xna.Framework.GameComponent
{
    private LetterSquare square1;
    private LetterSquare square2;
    public LetterRect()
    {
        square1 = new LetterSquare(this);
        square2 = new LetterSquare(this);
    }
}

public class LetterSquare 
{
    public LetterRect LetterRectProp { get; private set; }
    public LetterSquare (LetterRect letterRect )
    {
        this.LetterRectProp = letterRect;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多