gpt4 book ai didi

C# - MyClass.MyProperty[东西]

转载 作者:太空狗 更新时间:2023-10-29 20:55:24 30 4
gpt4 key购买 nike

我想做某事,但不确定如何描述它。我有这门课

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")。

这可能吗?我需要向 Company 类添加什么?

提前致谢!

最佳答案

是的,这是可能的。您需要创建一个访问器类,如下所示:

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);
}

}

关于C# - MyClass.MyProperty[东西],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6407934/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com