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

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

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

 public class Employee
    {
        public Employee()
        {       
                


        
8条回答
  •  暖寄归人
    2021-02-08 04:19

    I tried this way and it worked for me:

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A(new A());
        }
    }
    
    public class A
    {
        public string Name { get; set; }
        public A a;
    
        public A() { }
        public A(A _a)
        {
            a = _a;
        }
    }
    

    Now you can use it in the Main() function like:

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A(new A());
            a.Name = "Roger";
            a.a.Name = "John";
            Console.WriteLine("{0}, {1}", a.Name, a.a.Name);
        }
    }
    

提交回复
热议问题