首页 > 解决方案 > 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; }
}

标签: c#

解决方案


是的,这没有问题。你可以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; }
}

推荐阅读