c# - 我可以有一个带有通用列表的类并将其公开为默认值吗

标签 c# generics

我基本上想在代码中做到这一点:

PersonList myPersonList;
//populate myPersonList here, not shown

Foreach (Person myPerson in myPersonList)
{
...
}

类声明

public class PersonList
{
 public List<Person> myIntenalList;

 Person CustomFunction()
 {...}
}

那么如何在我的类中公开“myInternalList”作为 Foreach 语句可以使用的默认值呢?或者我可以吗?原因是我有大约 50 个类目前正在使用 GenericCollection,我想将它们转移到泛型但不想重写大量内容。

最佳答案

你可以让 PersonList 实现 IEnumerable<Person>

public class PersonList : IEnumerable<Person>
{
    public List<Person> myIntenalList;

    public IEnumerator<Person> GetEnumerator()
    {
         return this.myInternalList.GetEnumerator();
    }

    Person CustomFunction()
    {...}
}

或者更简单,只需让 PersonList 扩展 List:

public class PersonList : List<Person>
{
    Person CustomFunction() { ... }
}

第一种方法的优点是不暴露 List<T> 的方法。 ,而如果您想要该功能,第二个更方便。此外,您应该将 myInternalList 设为私有(private)。

关于c# - 我可以有一个带有通用列表的类并将其公开为默认值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2389645/

相关文章:

c# - 如何在 Silverlight 中为 ObservableCollection<T> 创建 CollectionView

c# - 在 C# 中序列化泛型类

c# - 在 EF7 中添加多个相同类型的导航属性

Silverlight 中的 .Net 框架版本 : no List<T>. 查找方法?

swift - Codable 泛型 Swift 5

c# - 没有从 'System.Collections.Generic.IList<double>' 到 'System.Collections.IList' 的隐式引用转换

c# - 可以使用具有多个选项卡/工作表的 csv 吗?

c# - 将类添加到 anchor 链接

Java 在 medhot 中返回 ArrayList<MyObject> ,它返回一个接口(interface)的 ArrayList

java - 如何使用寺庙方法或泛型方法或其他方法优化我的代码?现在我必须编写类似的代码三遍