繁体   English   中英

C#—我们应该在getter方法中强制转换吗

[英]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; 
        }
    }
    ..
}

问题:我们应该将返回值从listPeople[name]Person吗?

谢谢

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

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

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

不,演员不是必需的。 字典的索引器已经被强类型化以返回Person (因为那是该字典的TValue )。 那是泛型的好处之一:)

当然,要发现这一点最简单的方法是删除了演员和看-如果字典索引没有被强类型的,你的代码会无法编译因为你一直在试图返回object (或任何)用于类型Person的索引器。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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