开发者

C# -- should we should cast for get in Indexer Method

开发者 https://www.devze.com 2023-03-06 18:45 出处:网络
public class PeopleCollection : IEnumerable { private Dictionary<string, Person> listPeople = new Dictionary<string, Person>();
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消