C#——我们应该在 Indexer Method 中转换为 get

标签 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

谢谢

最佳答案

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

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

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

关于C#——我们应该在 Indexer Method 中转换为 get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6033961/

相关文章:

c# - 如何阻止 DataGridView 自动选择行?

c# - 如何向多维数组添加新项目

c# - 如何使用c#从gmail读取电子邮件

c# - C# 6 中(自动)属性初始化语法之间的区别

c# - 可以强制对象在第 1 代或第 2 代而不是第 0 代中被垃圾回收吗?

c# - 摆脱临时文件夹中的 Crystal Report 生成的文件 - Visual Studio 2008

c# - 无法从 Gridview 获取值

c# - c# 中货币值(value)的 RegEx 验证

c# - 从我的 C# 程序的同一文件夹启动 .exe

c# - 无法在 Windows 7 中使用 C# 中的窗口服务计算系统空闲值