简体   繁体   中英

c# List and object

I want to create a new user and save it in my list. Im new in C#, and I don´t know how I´m going to solve this. I´m using list.

using MetroFramework.Forms;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;


        namespace SGE
        {
            public partial class Registar_Utilizador : MetroForm
            {
                string username, password, tipo;
                List<Pessoa> todos = new List<Pessoa>();
                List<Pessoa> novaListaPessoa = new List<Pessoa>();

                public Registar_Utilizador(List<Pessoa> todos)
                {
                    InitializeComponent();
                }

                private void metroButtonAdicionar_Click(object sender, EventArgs e)
                {
                    int i = 0;
                    Pessoa p = new Pessoa();
                    do
                    {
                        p.setusername(metroTextBoxUsername.Text);
                    }while(i < todos.Count && p.getusername() == todos[i++].getusername());

                }
            }
        }

[Error] Error 1 Use of unassigned local variable 'todos'

In your Registar_Utilizador, you don't need to pass the list. You are doing nothing with it that I see.

public Registar_Utilizador(List<Pessoa> todos)
            {
                InitializeComponent();
            }

Now for this method: you will change it to below - I have shown using foreach:

 private void metroButtonAdicionar_Click(object sender, EventArgs e)
 {        
    foreach(Pessoa p in todos)
    {
        if (someCondition) //p.getusername() == todos[i++].getusername()
        {
          p.setusername(metroTextBoxUsername.Text);
          novaListaPessoa.Add(p)
        }
    }   
}

if you want to create a new instance of objects in todos, then you can use information from here to copy one object to another copy one object to another

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