[英]C# — should we should cast for get in Indexer Method
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; }
对于listPeople
字段中的Dictionary<string, Person>
,将TValue
替换为Person
,因此索引器将返回对Person
对象的引用。
不,演员不是必需的。 字典的索引器已经被强类型化以返回Person
(因为那是该字典的TValue
)。 那是泛型的好处之一:)
当然,要发现这一点最简单的方法是删除了演员和看-如果字典索引没有被强类型的,你的代码会无法编译因为你一直在试图返回object
(或任何)用于类型Person
的索引器。
不需要,但这不是必须的,但是如果您删除了(Person)并对其进行了编译,您将会发现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.