简体   繁体   中英

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; 
        }
    }
    ..
}

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 .

不需要,但这不是必须的,但是如果您删除了(Person)并对其进行了编译,您将会发现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM