Get object content without knowing the attribute name

2

In JavaScript I have, for example, the object:

var meuCarro = {
    fabricacao: "Ford",
    modelo: "Mustang",
    ano: 1969
};

And to access its contents, when I do not know the name of the attribute, I can access this way:

var atributo = "modelo"; //o nome do atributo obtenho via run time
var conteudo = meuCarro[atributo];

How can I do this in C #? The only way I know this language is, for example, string conteudo = meuCarro.modelo , but I can not solve my problem so because I get the attribute name in run time .

    
asked by anonymous 13.04.2018 / 16:08

3 answers

5

If you already have the class and do not know anything about it, and it is fully dynamic you really should use reflection so you can use variables instead of the name. You have a complex example in another response .

If you are going to create the object and want the same JavaScript semantics you should use a dictionary instead of a class, after all in JS the object is actually a dictionary. I already answered with an example . Actually in several examples .

If you do not know what to access then you should use dynamic , but you should avoid it whenever possible because C # is not a dynamic typing language . Example .

One last solution . Of course, it has even more complicated solutions.

By the comments I would go from switch , extensive code is not justification for using reflection, the code gets absurdly slower. If you do not want to write the code write a code generator, C # has more and more tools to help with this. But if you still insist on not writing the pure code, at least consider using a dictionary, by the description of the question and comment is what you need. Almost always reflection is gambiarra.

One last tip: what you want is a field and not the attribute , I know they taught you so, but taught wrong, use the correct terminology to avoid confusion.

    
13.04.2018 / 17:50
2

You can use Reflection to get the list of all attributes of the object and then with linq select which you want, follow example

public class Carro//Classe
{
    public int CarroId { get; set; }
    public string Modelo { get; set; }
    public string Marca { get; set; }
}

public static class Service//Service, utilizada para criar o metodo que irá retornar 
{
    public static PropertyInfo[] GetProperties(object obj)
    {
        return obj.GetType().GetProperties();
    }
}
class Program
{
    static void Main(string[] args)
    {
        //Declara novo objeto
        Carro car = new Carro
        {
            CarroId = 1,
            Modelo = "Fiesta",
            Marca = "Ford"
        };

        //Pega o array de todas propriedades do objeto carro
        var properties = Service.GetProperties(car);

        //Atributo
        var atributo = "Modelo";

        //Seleciona o valor do atributo pelo nome, utilizando linq
        var atributoSelecionado = properties.Where(p => p.Name == atributo).FirstOrDefault().GetValue(car,null);

        //foreach para varrer todas propriedades e pegar o nome e valor de cada uma
        foreach (var p in properties)
        {
            string name = p.Name;
            var value = p.GetValue(car, null);
        }
    }
}

Also, place in .NET Fiddle for reference

    
13.04.2018 / 16:34
1

Through reflection

string atributo = "modelo"
string conteudo = meuCarro.GetType().GetProperty(atributo).GetValue(meuCarro);
    
13.04.2018 / 16:43