Can a Custom C# object contain a property of the same type as itself?

后端 未结 8 1307
情深已故
情深已故 2021-02-08 04:03

If I have created the following Employee object (simplified)...

 public class Employee
    {
        public Employee()
        {       
                


        
相关标签:
8条回答
  • 2021-02-08 04:32

    First, the answer is Yes an object can have a field that contains an instance of itself. It can even have methods that accept or return the instances of the same class, and it can even depend on itself in the definition of the class, e.g:

    public class Person : IComparable<Person> //legal, recursive definition
    {
       //fields (or properties) that are of type Person
       public Person Father;
       public Person Mother;
       public List<Person> Children;
    
       // method that takes a Person as a parameter
       public bool IsParent(Person potentialParent)
       {
          ....
       }
    
       //method that returs a Person
       public Person Clone()
       {
          //TODO: real implementation coming soon
       }
    
       public Person(){}
    
       //constructor that takes persons as arguments
       public Person(Person father, Person Mother)
       {
          Father = father;
          Mother = mother;
       }
    }
    

    By default all reference values are null'd so you won't have a constructor problem unless you create one yourself. So, Yes, there can be some issues with circular references and endless loops (each parent has children that have children that have parents etc...) but usually they can be trivially detected and avoided.

    The only times I've encountered these kind of problems is when I used XML (or other text-based) serialization on circularly referenced objects.

    0 讨论(0)
  • 2021-02-08 04:36

    Specifically on the issue of construction (I've +1'd Odeds answer) - as you say constructing an instance in the constructor is a bad move.

    But then ask yourself - why would you ever need to anyway. In your Manager/Employee case - you can't always be sure that an employee always has a manager, and if they don't then you shouldn't be using a newed empty instance to signify that, but a null.

    When your type will have public get/set accessors on the properties, generally you're likely to be loading these object trees from some external source, in which case you have nothing to worry about. Equally, you can have a constructor that accepts other Employee instances for Manager/Employee relationships etc.

    You should also be checking for circular relationships in that constructor as well - i.e. an employee can't be someone's manager and their employee - try walking the child->parent relationship for that and see if it ever ends!

    0 讨论(0)
提交回复
热议问题