[英]How to refer to an array without creating a new one?
I want to refer to my USERS list in a form without having to create a new instance of the class the list is stored in as it creates a new list. 我想以一种形式引用我的用户列表,而不必在创建新列表时创建该列表所存储的类的新实例。
The LoginHandler class where the list is created and is added to. 创建列表并将其添加到的LoginHandler类。
namespace BG
{
public class LoginHandler
{
public List<User> users = new List<User>();
public LoginHandler()
{
users = new List<User>();
}
The form will consist of a for loop which loops to the count of items in the list so i need to refer back to it but do not want to have to create a new instance of class its in because that makes a new list which i do not want. 该表单将包含一个for循环,该循环循环到列表中的项目数,因此我需要引用它,但又不想创建一个新的class实例,因为它会创建一个新的列表,不想。
I think what you want is a property that returns a reference to a IEnumerable object. 我认为您想要的是一个返回对IEnumerable对象的引用的属性。
public class LoginHandler
{
private List<User> users = new List<User>();
public IEnumerable<User> Users { get { return users; } }
}
Then you can access the property without creating a copy or exposing the internal data members. 然后,您可以访问属性而无需创建副本或公开内部数据成员。
LoginHandler handler = new LoginHandler();
foreach (var user in handler.Users)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.