c# - C# - 对通用集合的自我引用
问题描述
如果我们创建一个像下面这样的类,它会抛出错误吗?由于 StudentCollection 指的是同一个类。哪一个是正确的?
1.
public class StudentDetail
{
public Collection<StudentDetail> StudentCollection { get; set; }
public string StudentName { get; set; }
public Guid StudentID { get; set; }
public int RollNo { get; set; }
public Guid ClassID { get; set; }
}
2.
public class StudentDetail
{
public Collection<studentinfo> StudentCollection { get; set; }
}
Public class studentinfo
{
public string StudentName { get; set; }
public Guid StudentID { get; set; }
public int RollNo { get; set; }
public Guid ClassID { get; set; }
}
解决方案
是的,这没有问题。你可以Collection<ThisClass>
在一个类中拥有一个,就像你也可以在一个类型中拥有一个相同类型的成员一样。例如,这也是完全有效的:
class Person
{
Person Mother { get; set; }
}
所以问题仍然存在,如果它是最佳实践。在我看来不是,因为您说每个实例也是其自身的集合。你应该有一个像这样持有它的类:
class University
{
IEnumerable<StudentInfo> Students { get; set; }
}
但有时如果我们举第一个例子可能是正确的:
class Person
{
Person Mother { get; set; }
IEnumerable<Person> Children {get; set; }
}
推荐阅读
- javascript - 如何根据 lastFocusedWindow 对 getAllwindows 的结果进行排序?
- c# - 动态访问实体框架 DbSet
- java - synchronized(){} 的异步(非阻塞)版本
- fullcalendar - 如何使用 fullcalendar v4 将事件保存在数据库中
- laravel - Laravel 在分页结果中附加值
- sql - Sqlite 第二个日期大于第一个日期
- c# - Botframework v4:弹出窗口
- ios - 如何在相机胶卷的特定位置插入新创建的 PHAsset?
- html - BeautifulSoup 不读取请求获得的“完整”HTML
- javascript - 如何根据屏幕大小和 li 标签数量制作响应式列表