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?*开发者_StackOverflow中文版*
}
set {
listPeople[name] = value;
}
}
..
}
Question: should we cast the return value from listPeople[name]
to Person
?
Thank you
No, it is not needed. In Dictionary<TKey, TValue>
the indexer is declared as:
public TValue this[TKey key] { get; set; }
For the Dictionary<string, Person>
in the listPeople
field, TValue
is replaced with Person
, so the indexer will return a reference to a Person
object.
No, that cast isn't necessary. Dictionary's indexer is already strongly typed to return Person
(because that's what TValue
is for that dictionary). That's one of the benefits of generics :)
Of course, the simplest way to find this out would be to remove the cast and see - if the Dictionary indexer hadn't been strongly typed, your code would have failed to compile as you'd have been trying to return object
(or whatever) for an indexer of type Person
.
No this is not necessary but you would have found out if you removed the (Person) and compiled it.
精彩评论