我想做点什么,但不知道如何描述它.我有这门课
public class Company { private List<Person> _persons; private Person GetPersonByName(string name) { // My code to select Person is here,which is fine } }
但我希望能够做到这一点
Company c; Person p = c.Persons["John"];
应隐式调用GetPersonByName(“John”).
那可能吗?我需要向公司课程添加什么?
提前致谢!
解决方法
是的,这是可能的.您需要创建一个访问者类,如下所示:
public class Company { private List<Person> _persons; public class PersonsIndexer { Company _owner; public PersonsIndexer(Company owner) { _owner = owner; } public Person this[string name] { get { return _owner._persons.FirstOrDefault(x=>x.Name == name); // or whatever code you have there } } } public PersonsIndexer Persons{ get; private set; } public Company() { Persons = new PersonsIndexer(this); } }