當我在Parent和Child之間建立關聯時,我的代碼看起來如此複雜。關聯Parent和Child數據模型對象的最佳方式是什麼?
問題:關聯Parent和Child數據模型對象的最佳方式是什麼?
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;
}
}
我會刪除chid.Parent = Child構造函數的parent,parent.AddChild已經做到了。你只是在重複自己。也許讓Child的構造函數是私有的,添加一個creater方法,將父類作爲輸入和其他屬性,創建孩子並使用父母的AddChild方法(簡單地說它是一個單身人士) – hazimdikenli 2011-02-07 12:53:03