自定义 C# 对象是否可以包含与自身类型相同的属性? [英] Can a Custom C# object contain a property of the same type as itself?

查看:184
本文介绍了自定义 C# 对象是否可以包含与自身类型相同的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建了以下 Employee 对象(简化)...

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

 public class Employee
    {
        public Employee()
        {       
        }

        public String StaffID { get; set; }
        public String Forename { get; set; }
        public String Surname { get; set; }
    }

...是否可以在 Employee 对象中拥有另一个属性,其类型也为 Employee 以保存其经理的详细信息(如下所示)?

... would it be acceptable to have another property in the Employee object with a Type also being Employee to hold their Manager's details (as shown below)?

 public class Employee
    {
        public Employee()
        {       
        }

        public String StaffID { get; set; }
        public String Forename { get; set; }
        public String Surname { get; set; }

        public Employee Manager { get; set; }
    }

此外,为 Manager 属性实例化 Employee 对象的最佳方法是什么?显然在构造函数中包含 this.Manager = new Employee(); 会导致无限循环.继承自 EmployeeManager 类是否是最好的方法(即使所有属性都相同)?

Also, what is the best way to instantiate the Employee object for the Manager property? Obviously including this.Manager = new Employee(); in the constructor will cause an infinite loop. Would a Manager class that inherrits from Employee be the best way (even though all the properties would be identical)?

推荐答案

一个对象可以确实有一个对它自己类型的对象的引用.

An object can indeed have a reference to an object of its own type.

这是大多数 Node 类型对象的实现方式.

This is how most Node type objects are implemented.

至于实例化 - 您可以传入 Employee 对象以用作经理(传入 null 表示没有经理).构造函数可以有多个重载:

As for instantiation - you can pass in the Employee object to use as manager (passing in null for no manager). Constructors can have multiple overloads:

public Employee(Employee manager)
{
   this.Manager = manager;
}

这篇关于自定义 C# 对象是否可以包含与自身类型相同的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆