Receive by Parameter and Manipulate a Generic Object LIST

Asked

Viewed 836 times

3

I need to receive an Object List by parameter Generic and manipulate, although researching did not understand right how to do.

Example:

public class Funcionario
{
    public long Id {get; set;}
    public string Nome {get; set;}
    public DateTime DataContrato {get; set;}
}

public class Professor
{
    public long Id {get; set;}
    public string Nome {get; set;}
    public bool IsAtivo {get; set;}
}

public void Reload(List<objeto> GridListaObjeto, int qtde)
{
    foreach (var obj in GridListaObjeto)
    {
        string sId = obj.Id;
        string sNome = obj.Nome;
    }
}

1 answer

2


The class List<T> is implemented in a generic way. Where T the class from which you want to create the list.

For example, to use a list of teachers, your method should receive as a parameter a List<Professor> professores. Would look like this:

public void Reload(List<Professor> professores, int qtde)
{
    foreach(Professor p in professores)
    {
        string sId = p.Id;
        string sNome = p.Nome;
    }
}

To Aluno would be the same thing, would change only the kind.

Now, if in your case you actually get a List<Object>, to access the properties Id and Nome, you need to ensure that the object instance of the Object type is of the Professor or Aluno. For this you can use the is. Behold:

public void Reload(List<Object> objects, int qtde)
{
    if(objects[0] is Professor) 
    {
        foreach(Object obj in objects)
        {
            Professor p = (Professor) obj;
            string sId = p.Id;
            string sNome = p.Nome;
        }
    }
}

Of course there are more "elegant" implementations, but for didactic purposes, that’s it hehe. Again, to Aluno is the same thing, just change the type of Professor for Aluno.

  • Instantiate in main a generic type list and initialize it within the method?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.