Receive by Parameter and Manipulate a Generic Object LIST

3

I need to get a Generic Object List parameter and manipulate it, although I do not understand how to do it.

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;
    }
}
    
asked by anonymous 20.01.2017 / 23:25

1 answer

2

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

For example, to use a teacher list, your method should be set to List<Professor> professores . It 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;
    }
}

For Aluno would be the same, it would only change the type.

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

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, for Aluno is the same, just change the type from Professor to Aluno .

    
21.01.2017 / 11:52