gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:04:06 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com