Access Object Property with a string

4

Student:

public class Aluno{
     public int Id { get; set; }
     public string Nome { get; set; }
     public string Sobrenome { get; set; }
}

Now I need to access the student's First and Last Name through a string, how can I do this?

EX.:

string opcaoA = "Nome";

var resultado = Aluno + ".opcaoA ";
//Resultado = "João";
    
asked by anonymous 20.01.2017 / 17:39

1 answer

5

If I understood your question correctly, you can use Reflection, here is a practical example to help you:

Class

public class Cidade
{
    public string Nome { get; set; }
}

Static Method to Get Property Value

public static object PegaValorPropriedade(object obj, string propName)
{
    return obj.GetType().GetProperty(propName).GetValue(obj, null);
}

Page

protected  void Page_Load(object sender, EventArgs e)
{
    var cid = new Cidade();
    cid.Nome = "Jose";
    object ed = PegaValorPropriedade(cid, "Nome");
    Response.Write(ed.ToString());
    //Imprime José
}
    
20.01.2017 / 17:45