反思性协会C#

时间:2016-12-06 14:52:49

标签: c# oop

我正在尝试在C#sharp中实现反身关联,但无法在网络上找到任何示例。 我想出了以下

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 marry员工jhonJunoirs自动添加到汤姆Last message related emails ${from} ${to} ${cc}列表中?

1 个答案:

答案 0 :(得分: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);
    }
}