2016-12-06 95 views
0

我試圖在C#中實現自反聯想,但在網上找不到任何示例。 我想出了以下Reflexive Association C#

class Employee 
{ 
    public string Name { get; set; } 
    public Employee Boss { get; set; } 
    public List<Employee> Junoirs; 
    public Employee (string name) 
    { 
     Junoirs = new List<Employee>(); 
     Name = name; 
    } 

    static void Main(string[] args) 
    { 
     Employee tom = new Employee("Tom"); 
     Employee marry = new Employee("Marry"); 
     Employee jhon = new Employee("Jhon"); 
     Employee foo = new Employee("Foo"); 
     Employee bar = new Employee("Bar"); 

     tom.Junoirs.AddRange(new Employee[] { marry, jhon }); 
     marry.Boss = tom; 
     jhon.Boss = tom; 

     marry.Junoirs.AddRange(new Employee[] { foo, bar }); 
     foo.Boss = marry; 
     bar.Boss = marry; 
    } 
} 

這是自反關聯的一個有效的例子嗎? 我如何自動添加tom作爲Boss員工marryjhon我將它們添加到湯姆的列表Junoirs

+1

請將該類的名稱更改爲「Juniors」 – Phiter

+0

創建一個名爲例如「 「AddJunior(...)」它設置關係的兩邊 – stuartd

+0

@PhiterFernandes btw'Junoirs'不是一個類,感謝指出錯字,雖然 –

回答

0

您可以使用方法添加/刪除後輩。 如果您需要需要 Juniors屬性的添加/刪除功能,您可以實現自己的IList或ICollection來處理簿記。

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

    public Employee Boss 
    { 
     get { return _boss; } 
     set 
     { 
      _boss?.RemoveJunior(this); 
      value?.AddJunior(this); 
     } 
    } 


    public IReadOnlyList<Employee> Juniors => _juniors.AsReadOnly(); 

    private Employee _boss = null; 
    private readonly List<Employee> _juniors = new List<Employee>(); 

    public Employee(string name) 
    { 
     Name = name; 
    } 

    public void AddJunior(Employee e) 
    { 
     // Remove from existing boss' list of employees 
     // Can't set Boss property here, that would create infinite loop 
     e._boss?.RemoveJunior(e); 
     _juniors.Add(e); 
     e._boss = this; 
    } 

    public void RemoveJunior(Employee e) 
    { 
     _juniors.Remove(e); 
     e._boss = null; 
    } 
} 

public class EmployeeTests 
{ 
    [Fact] 
    public void SettingBoss_AddsToEmployee() 
    { 
     var b = new Employee("boss"); 
     var e1 = new Employee("1"); 

     e1.Boss = b; 

     Assert.Same(b, e1.Boss); 
     Assert.Contains(e1, b.Juniors); 
    } 

    [Fact] 
    public void AddEmployee_SetsBoss() 
    { 
     var b = new Employee("boss"); 
     var e1 = new Employee("1"); 

     b.AddJunior(e1); 

     Assert.Same(b, e1.Boss); 
     Assert.Contains(e1, b.Juniors); 
    } 

    [Fact] 
    public void NullBoss_RemovesEmployee() 
    { 
     var b = new Employee("boss"); 
     var e1 = new Employee("1"); 

     b.AddJunior(e1); 
     e1.Boss = null; 

     Assert.Null(e1.Boss); 
     Assert.DoesNotContain(e1, b.Juniors); 
    } 

    [Fact] 
    public void RemoveEmployee_NullsBoss() 
    { 
     var b = new Employee("boss"); 
     var e1 = new Employee("1"); 

     b.AddJunior(e1); 

     b.RemoveJunior(e1); 

     Assert.Null(e1.Boss); 
     Assert.DoesNotContain(e1, b.Juniors); 
    } 
}