C# - 对Generic Collection的自我引用

Ask*_*_SO -3 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; }
    }
Run Code Online (Sandbox Code Playgroud)

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; }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 6

是的,这没有问题.您可以Collection<ThisClass>在类中拥有一个类,也可以在类型中拥有相同类型的成员.例如,这也是完全有效的:

class Person
{
    Person Mother { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

所以问题仍然是它是否是最佳实践.在我看来不是,因为你说每个实例也是它自己的集合.你应该有一个像这样持有它的类:

class University
{
    IEnumerable<StudentInfo> Students { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们采用第一个例子,有时可能是正确的:

class Person
{
    Person Mother { get; set; }
    IEnumerable<Person> Children {get; set; }
}
Run Code Online (Sandbox Code Playgroud)