具有以下对象:
public class Employee
{
public string LastName { get; set; } = "";
internal class SubordinateList<T> : List<T>, IPublicList<T> where T : Employee
{
public new void Add(T Subordinate) { }
}
public IPublicList<Employee> Subordinates = new SubordinateList<Employee>();
}
下级列表对象位于Employee对象内部,以某种方式使Employees成为下级列表的父对象。
如果我们把这个代码放在下面:
Anakin = New Employee();
Luke = New Employee();
Anakin.Subordinates.Add(Luke);
第三行将触发次级列表的方法"添加"。我想获得下级列表的父级的当前实例,如下所示:
public new void Add(T Subordinate)
{
T Manager = Subordinate.ParentInstance;
// then it will be possible to see the current value of
// the property "LastName" for Anakin with "Manager.LastName"
}
您不能这样做,因为您没有对管理器的引用。这就是我将如何实现它:
public class Employee
{
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string HiredDate { get; set; } = "";
private List<Employee> _subordinates = new List<Employee>();
public ReadOnlyCollection<Employee> Subordinates => _subordinates.AsReadOnly();
public void AddSubordinate(Employee employee)
{
_subordinates.Add(Employee);
//the manager is 'this'
var managerLastName = this.LastName;
}
}
将从属列表公开为ReadOnlyCollection
允许其他类读取列表,但阻止它们直接更新列表。因此,只有AddSubordinate()
方法可以用于添加员工,您可以根据经理的信息执行所需操作。