开发者

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?*开发者_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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜