实例化具有对象类型本身属性的对象

时间:2014-09-22 05:11:00

标签: c# oop

是否有更好的实例化对象的方法,例如,其中包含与属性相同的类型。如下例所示,我有一个Employee类,其中包含Employee类型的属性Manager,

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

    public Employee Manager { get; set; }


}

如果实例化

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

实例化将持续到我们现在达到顶级,以防组织层次结构很大(请假设可能是500级)是否有更好的实例化方法。

3 个答案:

答案 0 :(得分:1)

为什么不声明:

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 };
   }
}

像这样使用它:

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

答案 1 :(得分:0)

嵌套类是在另一个类的声明中声明的类

你所描述的是嵌套实例,你做得很好。

这是一个嵌套类:

class MyOuterClass {
    string outerClassName { get; set; }

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

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

大多数情况都没有要求内部阶级。

答案 2 :(得分:0)

//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;
       }
    }   

}

这样的东西?