简体   繁体   中英

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.

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.

I think what you want is a property that returns a reference to a IEnumerable object.

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)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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