public class PeopleCollection : IEnumerable
{
private Dictionary<string, Person> listPeople = new Dictionary<string, Person>();
// This indexer returns a person based on a string index.
public Person this[string name]
{
get {
return (Person)listPeople[name]; // **Is this cast necessary?**
}
set {
listPeople[name] = value;
}
}
..
}
问题:我们是否应该将 listPeople[name]
的返回值转换为 Person
?
谢谢
最佳答案
不,不需要。在 Dictionary<TKey, TValue>
索引器声明为:
public TValue this[TKey key] { get; set; }
对于 Dictionary<string, Person>
在listPeople
领域,TValue
替换为 Person
, 因此索引器将返回对 Person
的引用对象。
关于C#——我们应该在 Indexer Method 中转换为 get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6033961/