C# - 我们应该为了获取Indexer方法而进行转换

时间:2011-05-17 16:20:41

标签: c#

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吗?

谢谢

3 个答案:

答案 0 :(得分:3)

不,不需要。在Dictionary<TKey, TValue>中,索引器声明为:

public TValue this[TKey key] { get; set; }

对于Dictionary<string, Person>字段中的listPeopleTValue已替换为Person,因此索引器将返回对Person对象的引用。< / p>

答案 1 :(得分:2)

不,那个演员阵容没有必要。 Dictionary's indexer已经强类型化以返回Person(因为那是该字典的TValue)。这是仿制药的好处之一:)

当然,找到这个的最简单方法是删除强制转换并查看 - 如果字典索引器没有强类型,那么你的代码将无法编译。 d一直在尝试为object类型的索引器返回Person(或其他)。

答案 2 :(得分:1)

不,这不是必要的,但你会发现你是否删除了(人)并编译了它。