[英]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, 如下例所示,我有一个Employee类,其中包含Employee类型的Property Manager,
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. 如果组织层次结构庞大(请假设可能是500个级别),那么实例化将一直持续到我们达到最高级别为止。
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 ? 像这样吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.