关联父级和子级数据模型对象的最佳方法是什么?
在父子之间建立关联时,我下面的代码看起来非常复杂。
问题:关联父级和子级数据模型对象的最佳方式是什么?
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;
}
}
My code below looks so complicated when making association between Parent and Child.
Question: What is the best way to associate Parent and Child data model object?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您应该在类中实现一些辅助方法,其中封装了一些基本思想:
Maybe you should implement some helper methods into the class, which encapsulate some basic thinks:
这个问题可能会有所帮助:
C# 中的树数据结构
This question might help:
Tree data structure in C#