簡體   English   中英

自定義 C# 對象可以包含與自身相同類型的屬性嗎?

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

如果我創建了以下Employee<\/strong>對象(簡化)...

 public class Employee
    {
        public Employee()
        {       
        }

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

一個對象確實可以引用<\/strong>它自己類型的對象。

這是大多數Node<\/code>類型對象的實現方式。

至於實例化 - 您可以傳入Employee<\/code>對象以用作經理(傳入null<\/em>表示沒有經理)。 構造函數可以有多個重載:

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

是的,一個對象可以包含對同一類的其他對象的引用。

其次,我不會在 cunstructor 中創建一個新的 Employee 而是像這樣注入它:

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

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

    public Employee Manager { get; set; }
}

唯一不可能<\/em>的情況是使用struct<\/code> ; struct<\/code>是直接<\/strong>包含的(而不是對數據的固定大小的引用),因此Employee<\/code>結構的大小必須是“其他字段的大小加上 Employee 的大小”,這是循環的。

特別是你不能擁有:

struct Foo {
    Foo foo;
}

首先,答案是肯定<\/strong>的,一個對象可以有一個包含自身實例的字段。 它甚至可以具有接受或返回同一類的實例的方法,它甚至可以在類的定義中依賴於自身,例如:

public class Person : IComparable<Person> //legal, recursive definition
{
   //fields (or properties) that are of type Person
   public Person Father;
   public Person Mother;
   public List<Person> Children;

   // method that takes a Person as a parameter
   public bool IsParent(Person potentialParent)
   {
      ....
   }

   //method that returs a Person
   public Person Clone()
   {
      //TODO: real implementation coming soon
   }

   public Person(){}

   //constructor that takes persons as arguments
   public Person(Person father, Person Mother)
   {
      Father = father;
      Mother = mother;
   }
}

是的,您可以在Employee中擁有Employee並且它不會導致無限循環,默認情況下Employee對象的Manager屬性將為null

我試過這種方式,它對我有用:

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

它有效,您可以嘗試s.th。 喜歡:

public class A
{
    public A test { get; set; }
}

特別是關於構造問題(我已經+1'd Odeds 回答) - 正如你所說,在構造函數中構造一個實例是一個糟糕的舉動。

但然后問問自己——你為什么還需要這樣做。 在您的Manager / Employee案例中-您不能總是確定員工總是有經理,如果他們沒有,那么您不應該使用new的 ed 空實例來表示這一點,而是使用 null。

當您的類型將在屬性上具有公共 get/set 訪問器時,通常您可能會從某個外部源加載這些對象樹,在這種情況下您無需擔心。 同樣,您可以有一個構造函數來接受其他Employee實例以用於經理/員工關系等。

您還應該檢查該構造函數中的循環關系 - 即員工不能成為某人的經理和他們的員工 - 嘗試遍歷 child->parent 關系,看看它是否會結束!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM