Get object content without knowing the attribute name

Asked

Viewed 1,074 times

2

In Javascript I have, for example, the object:

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

And to access his content, when I don’t know the attribute name, I can access it 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’t solve my problem so because I get the attribute name in run time.

  • You will create an attribute in run time and then take its value?

  • @Barbetta, no... Attribute names will be stored in an array that was created in time design. In run time, through the index of the array I select from it a string with the name of the desired attribute and "printo" on the screen the contents.

  • Another way I can solve my problem is through if or case for each attribute, but the code would be too extensive.

3 answers

5


If you already have the class and know nothing about it, and it’s totally dynamic, you really should use reflection, so you can use variables instead of the name. Has a complex example in another answer.

If you are going to create the object and want the same Javascript semantics 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 you will access then you must use dynamic, but should avoid whenever possible because C# is not a dynamic typing language. Example.

A final solution. Of course, there are even more complicated solutions.

By the comments I would go from switch, Extensive code is no justification for using reflection, the code gets absurdly slower. If you don’t want to write the code write a code generator, C# has more and more tools to help with this (in 9 or 10 you will have very interesting features). But if you still insist on not writing the pure code, at least consider the use of a dictionary, by the description of the question and comments 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 that way, but they taught you wrong, use the right terminology to avoid confusion.

1

You can use Reflection to take the list of all attributes of the object and then with linq select which one 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 put in the .NET Fiddle for reference

0

Through

string atributo = "modelo"
string conteudo = meuCarro.GetType().GetProperty(atributo).GetValue(meuCarro);

Browser other questions tagged

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