简体   繁体   中英

Instantiate objects having a property of the object type itself

Is there a better way of instantiating an object say for example has the same type as a property in it. As in the example below, I have an Employee class containing property Manager of type Employee,

class Employee
{
    public string Name { get; set; }

    public Employee Manager { get; set; }


}

if instantiated

Employee n1 = new Employee{ 
   Name="emp1", 
   Manager = new Employee(){
      Name="mgr1", 
      Manager= new Employee(){ ...

The instantiation would go on till we reach the top level now in case the organization heirarchy is huge (please assume may be 500 levels) is there a better way to instantiate.

Well why not declarative:

class Employee
{
   public string Name { get; set; }
   public Employee Manager { get; set; }

   public static Employee CreateBigBoss(string name) // insert a enterprisey name here
   {
       return new Employee { Name = name, Manager = null };
   }

   public Employee CreateSubordinate(string name)
   {
       return new Employee { Name = name, Manager = this };
   }
}

use it like this:

var burns = Employee.CreateBigBoss("Mr Burns");
var smithers = burns.CreateSubordinate("Mr Smithers");

Nested classes are classes declared inside the declaration of another class.

What you are describing is nested instances and you did it fine.

This is a nested class:

class MyOuterClass {
    string outerClassName { get; set; }

    class MyInnerClass {
        string innerClassName { get; set; }
    }

    MyInnerClass myInnerClass = new MyInnerClass() {
        innerClassName = "inner";
    }
}

Most situations don't call for an inner class.

//this in main or whetever you use it.
Employee n1 = new Employee();
Employee manager = new Employee();
manager.IsCEO = true;
manager.Name = "Manager Name";

n1.Name = "John";
n1.Manager = manager;


class Employee
{
    private Employee _manager = new Employee();

    public string Name { get; set; }

    public bool IsCEO{ get; set;}

    public Employee Manager 
    { 
       get
       {
            if(IsCEO)
               return null;
            else
               return _manager;
       } 
       set
       {
            if(!IsCEO)
               _manager=value;
       }
    }   

}

Something like this ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM