2

在父子之间建立关联时,下面的代码看起来很复杂。

问题:关联父子数据模型对象的最佳方法是什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using ConsoleApplication1;

class Child
{
    public string Name { get; set; }
    public Parent Parent { get; set; }
}


class Parent
{
    public string Name { get; set; }
    public IEnumerable<Child> Children { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        Parent p1 = new Parent { Name = "P1" };

        Child c1 = new Child { Name = "C1" };
        c1.Parent = p1;

        Child c2 = new Child { Name = "C2" };
        c2.Parent = p1;


        List<Child> children = new List<Child>();
        children.Add(c1);
        children.Add(c2);

        p1.Children = children;
    }

}
4

3 回答 3

6

也许你应该在类中实现一些辅助方法,它封装了一些基本思想:

public class Parent {

....
    public void AddChild(Child child) {
        child.Parent = this;
        this.Children.Add(child);
    }

    public void RemoveChild(Child child) {
        child.Parent = null;
        this.Children.Remove(child);
    }
}


public class Child {
    private Child() {}

    public static Child CreateChild(Parent parent) {
        var child = new Child();
        parent.AddChild(child);
        return child;
    }
}
于 2011-02-07T11:54:26.070 回答
1

这个问题可能会有所帮助:

C#中的树数据结构

于 2011-02-07T11:53:23.640 回答
1
class Parent
{
  ...
  public Child AddChild(string name)
  {
    return this.AddChild(new Child(name));
  }

  public Child AddChild(Child c)
  {
    c.Parent = this;
    this.children.Add(c);

    return c;
  }
}
于 2011-02-07T11:56:10.293 回答