C# – MyClass.MyProperty [东西]

前端之家收集整理的这篇文章主要介绍了C# – MyClass.MyProperty [东西]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想做点什么,但不知道如何描述它.我有这门课
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);
    }

}
原文链接:https://www.f2er.com/csharp/98805.html

猜你在找的C#相关文章